Hibernate ddl-auto=update is not working - spring

Every time I restart my tomcat server all the data in the database tables are deleted. But I want to keep the data in the database tables. What I understood so far after reading several posts is that ddl-auto should be set to update.
In my spring boot application, I have following settings
security.basic.enabled=false
server.port=9090
spring.datasource.url=jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=myuser
spring.datasource.password=mypassword
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
hibernate.show_sql = true
hibernate.format_sql = true
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
Unfortunately, this is not working as expected. All data in the table is deleted.
This is log
2016-09-24 09:35:47.831 INFO 6343 --- [ost-startStop-1] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2016-09-24 09:35:47.852 INFO 6343 --- [ost-startStop-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2016-09-24 09:35:47.975 INFO 6343 --- [ost-startStop-1] org.hibernate.Version : HHH000412: Hibernate Core {4.3.11.Final}
2016-09-24 09:35:47.979 INFO 6343 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2016-09-24 09:35:47.982 INFO 6343 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2016-09-24 09:35:48.320 INFO 6343 --- [ost-startStop-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2016-09-24 09:35:48.954 INFO 6343 --- [ost-startStop-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2016-09-24 09:35:49.211 INFO 6343 --- [ost-startStop-1] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory
2016-09-24 09:35:49.861 INFO 6343 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2016-09-24 09:35:49.861 INFO 6343 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000102: Fetching database metadata
2016-09-24 09:35:49.866 INFO 6343 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000396: Updating schema
2016-09-24 09:35:49.882 INFO 6343 --- [ost-startStop-1] java.sql.DatabaseMetaData : HHH000262: Table not found: user
2016-09-24 09:35:49.885 INFO 6343 --- [ost-startStop-1] java.sql.DatabaseMetaData : HHH000262: Table not found: user
2016-09-24 09:35:49.887 INFO 6343 --- [ost-startStop-1] java.sql.DatabaseMetaData : HHH000262: Table not found: user
2016-09-24 09:35:49.907 INFO 6343 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000232: Schema update complete
What I really need is to keep the data in the database table, even after restarting my server.

It should work by specifing just those 2 properties:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:h2:file:./testdb
Tested with spring-boot 1.4.1.

If it still did't work try this(Spring boot 2.1)
Replace
spring.jpa.hibernate.ddl-auto=update
with
spring.jpa.hibernate.hbm2ddl.auto=update

Related

SpringBoot does not detect template of Thymeleaf

I started learning Thymeleaf templating with SpringBoot and my learning path was blocked by some implicit issue i could not find....
The issue is: SpringBoot app does not see template, although:
Controller looks like
Project structure includes /templates:
All required dependencies are in place:
Spring Boot log:
2022-11-13 22:21:13.196 INFO 20644 --- [ main]
com.coffeeshop.Application : Starting Application using
Java 11.0.10 on LAPTOP-O6B9USVI with PID 20644
(C:\Dev\Java\Projects\coffeeshop\build\classes\java\main started by
User in C:\Dev\Java\Projects\coffeeshop) 2022-11-13 22:21:13.196 INFO
20644 --- [ main] com.coffeeshop.Application :
No active profile set, falling back to 1 default profile: "default"
2022-11-13 22:21:13.588 INFO 20644 --- [ main]
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data
JPA repositories in DEFAULT mode. 2022-11-13 22:21:13.604 INFO 20644
--- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 23 ms. Found 1 JPA
repository interfaces. 2022-11-13 22:21:14.106 INFO 20644 --- [
main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized
with port(s): 8081 (http) 2022-11-13 22:21:14.106 INFO 20644 --- [
main] o.apache.catalina.core.StandardService : Starting service
[Tomcat] 2022-11-13 22:21:14.106 INFO 20644 --- [ main]
org.apache.catalina.core.StandardEngine : Starting Servlet engine:
[Apache Tomcat/9.0.64] 2022-11-13 22:21:14.184 INFO 20644 --- [
main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring
embedded WebApplicationContext 2022-11-13 22:21:14.184 INFO 20644 ---
[ main] w.s.c.ServletWebServerApplicationContext : Root
WebApplicationContext: initialization completed in 957 ms 2022-11-13
22:21:14.278 INFO 20644 --- [ main]
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing
PersistenceUnitInfo [name: default] 2022-11-13 22:21:14.309 INFO
20644 --- [ main] org.hibernate.Version :
HHH000412: Hibernate ORM core version 5.6.9.Final 2022-11-13
22:21:14.309 INFO 20644 --- [ main]
org.hibernate.cfg.Environment : HHH000205: Loaded
properties from resource hibernate.properties:
{hibernate.temp.use_jdbc_metadata_defaults=false,
hibernate.bytecode.use_reflection_optimizer=false} 2022-11-13
22:21:14.404 INFO 20644 --- [ main]
o.hibernate.annotations.common.Version : HCANN000001: Hibernate
Commons Annotations {5.1.2.Final} 2022-11-13 22:21:14.466 INFO 20644
--- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2022-11-13 22:21:14.796 INFO 20644 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-11-13 22:21:14.905 INFO 20644 --- [ main]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start
completed. 2022-11-13 22:21:14.921 INFO 20644 --- [ main]
o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using
JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-11-13 22:21:14.921 INFO 20644 --- [ main]
j.LocalContainerEntityManagerFactoryBean : Initialized JPA
EntityManagerFactory for persistence unit 'default' 2022-11-13
22:21:15.094 WARN 20644 --- [ main]
JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is
enabled by default. Therefore, database queries may be performed
during view rendering. Explicitly configure spring.jpa.open-in-view to
disable this warning 2022-11-13 22:21:15.298 INFO 20644 --- [
main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on
port(s): 8081 (http) with context path '' 2022-11-13 22:21:15.298
INFO 20644 --- [ main] com.coffeeshop.Application
: Started Application in 2.409 seconds (JVM running for 2.7)
When i check http://localhost:8081/home I got "home" string only.
Replace #RestController with #Controller. You cannot use #RestController because #RestController automatically adds #ResponseBody and Spring will only attempt to look up a view if #ResponseBody is not present.
This should fix your problem
#Controller
public class AppController {
#GetMapping("/")
public String viewHomePage() {
return "home";
}
}

How to create an H2+flyway test database in spring boot?

I have a spring boot project where I want to test my controller.I use MySql database for production but want an in memory database for running the testcases.I use Flyway for versioning database migration.I want my test database to use the same versioning.Can someone please help me with a way to do that?
This is what my application.properties in src/test/resources folder looks like:
# Database Properties
spring.jpa.database=H2
spring.database.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL;INIT=CREATE SCHEMA IF NOT EXISTS public;DATABASE_TO_UPPER=false
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
security.basic.enabled:false
spring.datasource.username:sa
spring.datasource.password:
# Flyway Properties
spring.flyway.locations=filesystem:src/main/resources/db/migration
spring.flyway.enabled=true
spring.flyway.baseline-on-migrate=true
This is my Test File:
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
#AutoConfigureMockMvc
#ContextConfiguration
public class PermissionsControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
public void existentUserCanGetTokenAndAuthenticationAndAlsoExtractPermissions() throws Exception {
String username = "Srishti";
String body = "{" + "\"username\":\"" + username + "\"}";
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/authenticate")
.contentType(MediaType.APPLICATION_JSON_VALUE).content(body)).andDo(print()).andExpect(status().isOk())
.andReturn();
String response = result.getResponse().getContentAsString();
mockMvc.perform(MockMvcRequestBuilders.get("/permission").header("Authorization", "Bearer " + response))
.andExpect(status().isOk()).andDo(print()).andReturn();
mockMvc.perform(MockMvcRequestBuilders.get("/permission/9").header("Authorization", "Bearer " + response))
.andExpect(status().isOk()).andDo(print()).andReturn();
}
}
And this is the output that I get currently get:
2020-09-06 19:30:54.481 INFO 26936 --- [ main] c.t.L.PermissionsControllerTest : Starting PermissionsControllerTest on DGKDSQ13 with PID 26936 (started by SrishtiChawla in C:\Users\srishtichawla\Desktop\LCTraining\LCTraining)
2020-09-06 19:30:54.483 INFO 26936 --- [ main] c.t.L.PermissionsControllerTest : No active profile set, falling back to default profiles: default
2020-09-06 19:30:55.599 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-09-06 19:30:55.600 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2020-09-06 19:30:55.670 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.LOBRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.672 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.PermissionsRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.674 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.ProductCategoryRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.677 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.RolesRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.679 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.ScoringModelSuiteRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.681 INFO 26936 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.training.LCtraining.repository.UserRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-09-06 19:30:55.682 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 74ms. Found 0 JDBC repository interfaces.
2020-09-06 19:30:55.694 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-09-06 19:30:55.695 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-09-06 19:30:55.762 INFO 26936 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 63ms. Found 6 JPA repository interfaces.
2020-09-06 19:30:56.308 INFO 26936 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler#1e5eb20a' of type [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-09-06 19:30:56.325 INFO 26936 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-09-06 19:30:57.018 INFO 26936 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 0 (http)
2020-09-06 19:30:57.032 INFO 26936 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-09-06 19:30:57.033 INFO 26936 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-09-06 19:30:57.216 INFO 26936 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-09-06 19:30:57.216 INFO 26936 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2708 ms
2020-09-06 19:30:57.353 WARN 26936 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-09-06 19:30:57.509 INFO 26936 --- [ main] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 6.4.4 by Redgate
2020-09-06 19:30:57.515 INFO 26936 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-09-06 19:30:57.746 INFO 26936 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-09-06 19:30:57.773 INFO 26936 --- [ main] o.f.c.internal.database.DatabaseFactory : Database: jdbc:h2:mem:testdb (H2 1.4)
2020-09-06 19:30:57.864 INFO 26936 --- [ main] o.f.core.internal.command.DbValidate : Successfully validated 9 migrations (execution time 00:00.036s)
2020-09-06 19:30:57.883 INFO 26936 --- [ main] o.f.c.i.s.JdbcTableSchemaHistory : Creating Schema History table "PUBLIC"."flyway_schema_history" ...
2020-09-06 19:30:57.955 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Current version of schema "PUBLIC": << Empty Schema >>
2020-09-06 19:30:57.970 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.1 - createTables
2020-09-06 19:30:58.100 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.2 - inservalues
2020-09-06 19:30:58.144 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.3 - altertable
2020-09-06 19:30:58.183 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.4 - INSERTVALUES2
2020-09-06 19:30:58.216 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.5 - insertvalues3
2020-09-06 19:30:58.241 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.6 - ALTERTABLE
2020-09-06 19:30:58.264 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.7 - Altertablelob
2020-09-06 19:30:58.293 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.8 - insertvals
2020-09-06 19:30:58.315 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema "PUBLIC" to version 1.10 - uniquekey
2020-09-06 19:30:58.330 INFO 26936 --- [ main] o.f.core.internal.command.DbMigrate : Successfully applied 9 migrations to schema "PUBLIC" (execution time 00:00.383s)
2020-09-06 19:30:58.541 INFO 26936 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-09-06 19:30:58.639 INFO 26936 --- [ task-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-09-06 19:30:58.711 INFO 26936 --- [ task-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.18.Final
2020-09-06 19:30:58.903 INFO 26936 --- [ task-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-09-06 19:30:59.060 INFO 26936 --- [ task-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2020-09-06 19:30:59.320 INFO 26936 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
2020-09-06 19:30:59.970 INFO 26936 --- [ task-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-09-06 19:30:59.982 INFO 26936 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-09-06 19:31:00.409 INFO 26936 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2020-09-06 19:31:00.489 INFO 26936 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#1c43e84e, org.springframework.security.web.context.SecurityContextPersistenceFilter#5e62ca19, org.springframework.security.web.header.HeaderWriterFilter#493968a9, org.springframework.web.filter.CorsFilter#7bd694a5, org.springframework.security.web.authentication.logout.LogoutFilter#322ab6ce, com.training.LCtraining.filter.JwtFilter#af9dd34, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#6528d339, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#3149409c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#21ce2e4d, org.springframework.security.web.session.SessionManagementFilter#780c0, org.springframework.security.web.access.ExceptionTranslationFilter#7a8b7e11, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#11ee671f]
2020-09-06 19:31:01.178 INFO 26936 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring TestDispatcherServlet ''
2020-09-06 19:31:01.179 INFO 26936 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Initializing Servlet ''
2020-09-06 19:31:01.195 INFO 26936 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Completed initialization in 16 ms
2020-09-06 19:31:01.298 INFO 26936 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 51516 (http) with context path ''
2020-09-06 19:31:01.300 INFO 26936 --- [ main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-09-06 19:31:01.785 INFO 26936 --- [ main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-09-06 19:31:01.801 INFO 26936 --- [ main] c.t.L.PermissionsControllerTest : Started PermissionsControllerTest in 7.711 seconds (JVM running for 9.214)
Hibernate: select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=?
2020-09-06 19:31:02.278 WARN 26936 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 42102, SQLState: 42S02
2020-09-06 19:31:02.279 ERROR 26936 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Table "user" not found; SQL statement:
select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=? [42102-200]
MockHttpServletRequest:
HTTP Method = POST
Request URI = /authenticate
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"22"]
Body = {"username":"Srishti"}
Session Attrs = {}
Handler:
Type = com.training.LCtraining.integration.UserRestController
Method = com.training.LCtraining.integration.UserRestController#generateToken(AuthRequest)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.dao.InvalidDataAccessResourceUsageException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 401
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = application/json
Body = {"timestamp":"2020-09-06","message":"could not prepare statement; SQL [select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement","details":"uri=/authenticate"}
Forwarded URL = null
Redirected URL = null
Cookies = []
MockHttpServletRequest:
HTTP Method = POST
Request URI = /authenticate
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"22"]
Body = {"username":"Srishti"}
Session Attrs = {}
Handler:
Type = com.training.training.integration.UserRestController
Method = com.training.training.integration.UserRestController#generateToken(AuthRequest)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.dao.InvalidDataAccessResourceUsageException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 401
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = application/json
Body = {"timestamp":"2020-09-06","message":"could not prepare statement; SQL [select user0_.user_id as user_id1_9_, user0_.lob_id as lob_id4_9_, user0_.enabled as enabled2_9_, user0_.role_id as role_id5_9_, user0_.username as username3_9_ from user user0_ where user0_.username=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement","details":"uri=/authenticate"}
Forwarded URL = null
Redirected URL = null
Cookies = []
2020-09-06 19:31:02.656 INFO 26936 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-09-06 19:31:02.659 INFO 26936 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-09-06 19:31:02.659 INFO 26936 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-09-06 19:31:02.664 INFO 26936 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
The controllers are working fine on the production side.
This is my V1.1__createtable.sql file
create table permissions(
permissionID int not null auto_increment,
permissionTitle varchar(40) not null,
permissionDescription varchar(255),
PRIMARY KEY (permissionID),
UNIQUE (permissionTitle));
insert into permissions(permissionTitle) values('Create Role');
insert into permissions(permissionTitle) values('Edit Role');
insert into permissions(permissionTitle) values('Delete Role');
insert into permissions(permissionTitle) values('Create User');
insert into permissions(permissionTitle) values('Edit User');
insert into permissions(permissionTitle) values('Delete User');
insert into permissions(permissionTitle) values('Create LOB');
insert into permissions(permissionTitle) values('Edit LOB');
insert into permissions(permissionTitle) values('Delete LOB');
According to the logs, Flyway is executed successfully:
Flyway Community Edition 6.4.4 by Redgate
HikariPool-1 - Starting...
HikariPool-1 - Start completed.
Database: jdbc:h2:mem:testdb (H2 1.4)
Successfully validated 9 migrations (execution time 00:00.036s)
Creating Schema History table "PUBLIC"."flyway_schema_history" ...
Current version of schema "PUBLIC": << Empty Schema >>
Migrating schema "PUBLIC" to version 1.1 - createTables
Migrating schema "PUBLIC" to version 1.2 - inservalues
Migrating schema "PUBLIC" to version 1.3 - altertable
Migrating schema "PUBLIC" to version 1.4 - INSERTVALUES2
Migrating schema "PUBLIC" to version 1.5 - insertvalues3
Migrating schema "PUBLIC" to version 1.6 - ALTERTABLE
Migrating schema "PUBLIC" to version 1.7 - Altertablelob
Migrating schema "PUBLIC" to version 1.8 - insertvals
Migrating schema "PUBLIC" to version 1.10 - uniquekey
Successfully applied 9 migrations to schema "PUBLIC" (execution time 00:00.383s)
You can see that 9 migrations are applied: createTables, inservalues, altertable, INSERTVALUES2, insertvalues3, ALTERTABLE, Altertablelob, insertvals, uniquekey.
Is this list complete or are you expecting more migrations?
The error you see later in the log comes from Hibernate, not from Flyway.
And it says:
Table "user" not found
Looking the migration names, I would expect that the user table is created by the createTables migration. But there's no CREATE TABLE 'user' statement in V1.1__createTables.sql.
Please double-check that all necessary tables are defined in your migrations. You should NOT alter old migrations. Instead, you can create new migrations for the missing tables and use CREATE TABLE IF NOT EXISTS syntax, so that it's compatible with existing production environment.
I had a similar problem and my solution was described in a comment by #Srish. Changing my url from jdbc:h2:mem:[MYDB] to jdbc:h2:file:~/[MYDB] allowed flyway to successfully perform the migrations as well perform JPA's validation.

Not Able to fetch table in Oracle Database after creating a table using JPA hibernate

I am trying to connect Oracle Database 12c using spring boot, and creating a table using JPA hibernate and code is running fine also in postman get and post working fine(request is hitting and tables are created). now when I am chekcing tables in my oracle database 12c I am getting output as table does not exist.
here is my database connection file
## Database Properties
#spring.datasource.url = jdbc:mysql://localhost:3306/detail?useSSL=false
spring.datasource.url= jdbc:oracle:thin:#<IP>:1521/<pdb database service name>
spring.datasource.username=sys as sysdba
spring.datasource.password=Welcome1
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=update
server.port=8081
spring.jpa.show-sql=true
This is my Output after executing the code
2020-01-31 16:06:40.916 WARN 7724 --- [ restartedMain] o.s.boot.StartupInfoLogger : InetAddress.getLocalHost().getHostName() took 5006 milliseconds to respond. Please verify your network configuration (macOS machines may need to add entries to /etc/hosts).
2020-01-31 16:06:45.927 INFO 7724 --- [ restartedMain] com.example.DemoApplication : Starting DemoApplication on Kirtis-Mac.local with PID 7724 (/Users/kirtijain/Downloads/demo/target/classes started by kirtijain in /Users/kirtijain/Downloads/demo)
2020-01-31 16:06:45.927 INFO 7724 --- [ restartedMain] com.example.DemoApplication : No active profile set, falling back to default profiles: default
2020-01-31 16:06:46.341 INFO 7724 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-01-31 16:06:46.342 INFO 7724 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2020-01-31 16:06:46.351 INFO 7724 --- [ restartedMain] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.example.repository.UserRepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-01-31 16:06:46.351 INFO 7724 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 8ms. Found 0 JDBC repository interfaces.
2020-01-31 16:06:46.358 INFO 7724 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-01-31 16:06:46.359 INFO 7724 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-01-31 16:06:46.365 INFO 7724 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 6ms. Found 1 JPA repository interfaces.
2020-01-31 16:06:46.506 INFO 7724 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.ws.config.annotation.DelegatingWsConfiguration' of type [org.springframework.ws.config.annotation.DelegatingWsConfiguration$$EnhancerBySpringCGLIB$$9bd21857] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-01-31 16:06:46.511 INFO 7724 --- [ restartedMain] .w.s.a.s.AnnotationActionEndpointMapping : Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
2020-01-31 16:06:46.523 INFO 7724 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-01-31 16:06:47.870 INFO 7724 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2020-01-31 16:06:47.872 INFO 7724 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-01-31 16:06:47.873 INFO 7724 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-01-31 16:06:47.950 INFO 7724 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-01-31 16:06:47.950 INFO 7724 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2016 ms
2020-01-31 16:06:48.059 INFO 7724 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-01-31 16:06:48.076 INFO 7724 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-3 - Starting...
2020-01-31 16:06:48.077 WARN 7724 --- [ restartedMain] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
2020-01-31 16:06:53.326 INFO 7724 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-3 - Start completed.
2020-01-31 16:06:53.326 INFO 7724 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle12cDialect
Hibernate: create table test_table (id number(19,0) generated as identity, created_by varchar2(50 char) not null, created_date timestamp, email_address varchar2(255 char) not null, first_name varchar2(255 char) not null, last_modified_by varchar2(50 char), last_modified_date timestamp, last_name varchar2(255 char) not null, primary key (id))
2020-01-31 16:07:02.689 INFO 7724 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-01-31 16:07:02.690 INFO 7724 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-01-31 16:07:02.699 INFO 7724 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-01-31 16:07:02.876 WARN 7724 --- [ restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-01-31 16:07:02.956 INFO 7724 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-01-31 16:07:03.142 INFO 7724 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2020-01-31 16:07:03.142 INFO 7724 --- [ restartedMain] com.example.DemoApplication : Started DemoApplication in 32.29 seconds (JVM running for 753.748)
2020-01-31 16:07:03.144 INFO 7724 --- [ restartedMain] .ConditionEvaluationDeltaLoggingListener : Condition evaluation unchanged
spring started
Result in Oracle Database
the tables are there so you probably connect to the wrong schema. You can see the schema where you are with
show user
You can find out where the table is querying the data dictionary with
select table_name, owner from all_tables where table_name = 'test_table';
One advice: it is a bad practise to connect as sys as sysdba from the application.
You should create a new schema (i.e. TEST) and connect with those credentials: aside the security aspects (your application cannot change everything in the database) you create by default tables (and any other object) in the designated Oracle schema.

API call failed : HHH000206: hibernate.properties not found Exception while changing Data Source of Spring Boot

I would like to change my data source from mariah DB to oracle 9i database .
When it comes to the execution, it gives the following exception. Do I need to modify my repository and model connecting to this database?
Error:
2019-11-08 12:29:04.011 INFO 16044 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.3.10.Final}
2019-11-08 12:29:04.013 INFO 16044 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-11-08 12:29:04.160 INFO 16044 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-11-08 12:29:04.356 INFO 16044 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle9iDialect
application.properties
// Server Port
server.port=4200
spring.datasource.url =jdbc:oracle:thin:#localhost:1521:dev
spring.datasource.username =ops$dev
spring.datasource.password =abc123sss
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.jpa.properties.hibernate.ddl-auto=create
spring.jpa.database-platform= org.hibernate.dialect.Oracle9iDialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle9iDialect
spring.jpa.hibernate.ddl-auto = true
And then, my screen tells Unable to connect instead of giving out string messages :

Spring boot stops as I write some JPA queries in the repository

I am using spring boot with H2 database. My application stops with below text on console.
2016-08-01 10:36:08.610 INFO 3920 --- [ost-startStop-1] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2016-08-01 10:36:08.651 INFO 3920 --- [ost-startStop-1] org.hibernate.Version : HHH000412: Hibernate Core {4.3.11.Final}
2016-08-01 10:36:08.651 INFO 3920 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2016-08-01 10:36:08.651 INFO 3920 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2016-08-01 10:36:08.801 INFO 3920 --- [ost-startStop-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2016-08-01 10:36:09.031 INFO 3920 --- [ost-startStop-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2016-08-01 10:36:09.131 INFO 3920 --- [ost-startStop-1] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory
2016-08-01 10:36:09.291 INFO 3920 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2016-08-01 10:36:09.291 INFO 3920 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000102: Fetching database metadata
2016-08-01 10:36:09.301 INFO 3920 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000396: Updating schema
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000261: Table found: TEST.PUBLIC.EMAILDATA
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000037: Columns: [quantity, emailto, id, autostart, emailfrom]
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000108: Foreign keys: []
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000126: Indexes: [primary_key_2]
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000261: Table found: TEST.PUBLIC.STATUS
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000037: Columns: [exchangefile, consolidate, processdate, aggregateall, scriptmaster, sendmail, id, insiderstrade]
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000108: Foreign keys: []
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] o.hibernate.tool.hbm2ddl.TableMetadata : HHH000126: Indexes: [primary_key_9]
2016-08-01 10:36:09.311 INFO 3920 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000232: Schema update complete
My repository is:
#Transactional
public interface EmailDataRepository extends JpaRepository<EmailData,Long>{
#Query("SELECT p FROM EmailData P")
public EmailData findLastRow();
}
And DBConfig is:
#Configuration
#EnableTransactionManagement
#ComponentScan("com.demo.*")
#PropertySource("classpath:application.properties")
#EntityScan(basePackages = {"com.demo.model"})
#EnableJpaRepositories("com.demo.repository.main")
public class DBConfig {....}
Model:
#Entity
#Table(name="EmailData")
public class EmailData {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Long id;
private String emailTo;
private String emailFrom;
private String quantity;
private Boolean autoStart;
...}
Your H2 database url should have the following configuration
DB_CLOSE_ON_EXIT=FALSE
Spring Boot documentation has a quote:
If, for whatever reason, you do configure the connection URL for an embedded database, care should be taken to ensure that the database’s automatic shutdown is disabled. If you’re using H2 you should use DB_CLOSE_ON_EXIT=FALSE to do so. If you’re using HSQLDB, you should ensure that shutdown=true is not used. Disabling the database’s automatic shutdown allows Spring Boot to control when the database is closed, thereby ensuring that it happens once access to the database is no longer needed.

Resources