I build a simple SpringBoot App (version: 2.4.3). I have the following Entity:
package com.ksteindl.logolo.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Foo {
#Id
private String id;
private String foo;
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
and an application.properties
spring.jpa.show-sql=true
spring.datasource.url = jdbc:mysql://localhost:3306/mysql
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL57Dialect
At first run, everything seems fine. The tables are created according to the Entites.
However, when I restart my app, I get exceptions for every Entity/Table I have. Moreover, if I modify my Entity (for example introduce a bar attribute in Foo Entity), the corresponding Table didn't change in the DB.
It seems to me, that it tries to re-create the tables, but I don't know why.
I got the following Exceptions for every Table/Entity I have:
Hibernate: create table foo (id varchar(255) not null, bar varchar(255), baz varchar(255), foo varchar(255), primary key (id)) engine=InnoDB
2021-04-02 16:34:17.000 WARN 16359 --- [ restartedMain] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "create table foo (id varchar(255) not null, bar varchar(255), baz varchar(255), foo varchar(255), primary key (id)) engine=InnoDB" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table foo (id varchar(255) not null, bar varchar(255), baz varchar(255), foo varchar(255), primary key (id)) engine=InnoDB" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559) [hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504) [hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:277) [hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:71) [hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:207) [hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114) [hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184) [hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73) [hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:318) [hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468) [hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1259) [hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) [spring-orm-5.3.4.jar:5.3.4]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.3.4.jar:5.3.4]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) [spring-orm-5.3.4.jar:5.3.4]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) [spring-orm-5.3.4.jar:5.3.4]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.3.4.jar:5.3.4]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1845) [spring-beans-5.3.4.jar:5.3.4]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782) [spring-beans-5.3.4.jar:5.3.4]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) [spring-beans-5.3.4.jar:5.3.4]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) [spring-beans-5.3.4.jar:5.3.4]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) [spring-beans-5.3.4.jar:5.3.4]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.4.jar:5.3.4]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) [spring-beans-5.3.4.jar:5.3.4]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) [spring-beans-5.3.4.jar:5.3.4]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1153) ~[spring-context-5.3.4.jar:5.3.4]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:907) ~[spring-context-5.3.4.jar:5.3.4]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:582) ~[spring-context-5.3.4.jar:5.3.4]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.3.jar:2.4.3]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767) ~[spring-boot-2.4.3.jar:2.4.3]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.4.3.jar:2.4.3]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) ~[spring-boot-2.4.3.jar:2.4.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) ~[spring-boot-2.4.3.jar:2.4.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1311) ~[spring-boot-2.4.3.jar:2.4.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1300) ~[spring-boot-2.4.3.jar:2.4.3]
at com.ksteindl.logolo.LogoloApplication.main(LogoloApplication.java:10) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_282]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_282]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_282]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_282]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.4.3.jar:2.4.3]
Caused by: java.sql.SQLSyntaxErrorException: Table 'foo' already exists
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.23.jar:8.0.23]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.23.jar:8.0.23]
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:762) ~[mysql-connector-java-8.0.23.jar:8.0.23]
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:646) ~[mysql-connector-java-8.0.23.jar:8.0.23]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-3.4.5.jar:na]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
... 40 common frames omitted
Can someone please help me? Thanks
In some cases, Hibernate is not able to make some changes on the database schema by itself.
That's why in general we try not to set ddl-auto to update and we prefer to use a data migration tool like liquibase or flyway.
In very simple cases like adding a column for example, Hibernate will work very well because it's a non breaking change. On the other hand, if you want to delete a column for example, it becomes more delicate. In this case your java entity will not know about this column anymore, but in the database it will still exist.
This is both a problem and a good thing because Hibernate makes sure that you don't lose data, but it is also the reason why some changes are not made.
As I told you above, we will prefer to use data migration tools, which are made to do this kind of things.
You can have a look at Liquibase for example, which is a very good tool.
Here are some useful links:
https://www.liquibase.org/
https://docs.liquibase.com/tools-integrations/springboot/springboot.html
https://www.baeldung.com/liquibase-refactor-schema-of-java-app
But you can also use flyway (which I don't know) : https://flywaydb.org/
And finally, here is a comparison between Liquibase and Flyway rather interesting: https://dzone.com/articles/flyway-vs-liquibase
It looks like in 2.4.3 SpringBoot JPA ddl-auto=update behavior doesn't work with MySql 8.
With PostgreSQL 13, the ddl-auto=update behavior works perfectly, without any error.
my application.yml
spring:
jpa:
hibernate:
ddl-auto: update
database-platform: org.hibernate.dialect.PostgreSQLDialect
datasource:
url: "jdbc:postgresql://localhost:5432/mydb"
username: myuser
password: mypassword
If someone can confrim/condtradict, that would be reassuring.
Related
I have issue deploying a new version of my app in tomcat. I got an exception for class which was an entity with #OneToOne relation to another entity class. In the new version of the app, the both classes are not entities anymore and don't have relation. Is appear is tried to clean the MySQL, but it fails on this step and I try the couple of tings online and still is not working, any help will be welcomed.
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: persistent class not known: com.mikegrep.TwitterModel.PublicMetrics
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:421)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)
... 25 more
Caused by: org.hibernate.MappingException: persistent class not known: com.mikegrep.TwitterModel.PublicMetrics
at org.hibernate.boot.internal.MetadataImpl.getIdentifierType(MetadataImpl.java:427)
at org.hibernate.type.EntityType.getIdentifierType(EntityType.java:603)
at org.hibernate.type.EntityType.getIdentifierOrUniqueKeyType(EntityType.java:643)
at org.hibernate.persister.entity.AbstractPropertyMapping.initIdentifierPropertyPaths(AbstractPropertyMapping.java:396)
at org.hibernate.persister.entity.AbstractPropertyMapping.initPropertyPaths(AbstractPropertyMapping.java:365)
at org.hibernate.persister.entity.AbstractEntityPersister.initOrdinaryPropertyPaths(AbstractEntityPersister.java:2629)
at org.hibernate.persister.entity.AbstractEntityPersister.initPropertyPaths(AbstractEntityPersister.java:2676)
at org.hibernate.persister.entity.AbstractEntityPersister.postConstruct(AbstractEntityPersister.java:4344)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:449)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:181)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:319)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409)
It seems like your PublicMetrics cannot be mapped correctly. Since it is not within a OneToMany relationship anymore you have to tell Hibernate how to serialize/deserialize it, e.g. using a javax.persistence.AttributeConverter. Its hard to make those assumptions without seeing the actual models, though.
I want to initialize both schema and domain for my in-memory h2 database for running Junit test cases but I face the below error. Is there a proper syntax to initialize both schema and domain on init?
Caused by: org.hibernate.exception.SQLGrammarException: Unable to open JDBC Connection for DDL execution
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:69)
at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcConnection(ImprovedExtractionContextImpl.java:60)
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:40)
at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.initializeSequences(DatabaseInformationImpl.java:65)
at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.<init>(DatabaseInformationImpl.java:59)
at org.hibernate.tool.schema.internal.Helper.buildDatabaseInformation(Helper.java:155)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:96)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:320)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391)
... 64 common frames omitted
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "CREATE SCHEMA IF NOT EXISTS INVENTORY CREATE[*] DOMAIN IF NOT EXISTS JSON AS TEXT"; SQL statement:
CREATE SCHEMA IF NOT EXISTS inventory create domain if not exists json as text [42000-200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:453)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
at org.h2.message.DbException.get(DbException.java:205)
at org.h2.message.DbException.get(DbException.java:181)
at org.h2.message.DbException.getSyntaxError(DbException.java:229)
at org.h2.command.Parser.getSyntaxError(Parser.java:1051)
at org.h2.command.Parser.prepareCommand(Parser.java:741)
at org.h2.engine.Session.prepareLocal(Session.java:657)
at org.h2.engine.Session.prepareCommand(Session.java:595)
at org.h2.engine.Engine.openSession(Engine.java:241)
at org.h2.engine.Engine.createSessionAndValidate(Engine.java:171)
at org.h2.engine.Engine.createSession(Engine.java:166)
at org.h2.engine.Engine.createSession(Engine.java:29)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:340)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:173)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:152)
at org.h2.Driver.connect(Driver.java:69)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:353)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:562)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:43)
... 78 common frames omitted
My property file for in-memory h2 database is below.
spring.datasource.url=jdbc:h2:mem:testdb;INIT=CREATE SCHEMA IF NOT EXISTS inventory create domain if not exists json as text;MODE=PostgreSQL;
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
You are using 2 SQL statements without separator ...
According to http://www.h2database.com/html/features.html#execute_sql_on_connection you may use '\;':
spring.datasource.url=jdbc:h2:mem:testdb;INIT=CREATE SCHEMA IF NOT EXISTS inventory\\; CREATE DOMAIN IF NOT EXISTS JSON AS TEXT;MODE=PostgreSQL;
I am developing a spring boot application where the primary database is MYSQL and for running JUnit test cases it is H2. I have also enabled multi-tenancy following the article here. The multi-tenancy part is working fine, when I start my application I can see that the configured schemas are created.
Now when I try to package my application using maven some test cases fail. And the reason for that is the schema validation is failing. Anyhow even if I disable the validation of schema I can see that the exceptions that I am getting are due to the fact that it is not able to find columns.
As an example, this is the model class.
#Data
#Entity(name="my_actual_values")
#ToString(exclude = {"tspSession"})
#EqualsAndHashCode(exclude = {"tspSession"})
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class SessionActualValue {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String ecu;
private String code;
private String actualValueName;
private String value;
private String measurementUnit;
#Temporal(TemporalType.TIMESTAMP)
private Date timestamp;
#ManyToOne(cascade = CascadeType.ALL)
private TspSession tspSession;
}
And for this the exception I get is
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [actualValueName] in table [session_actual_values]
Now when I try to fix for column "actualValueName" by annotating it with "#Column" in the model class and run the test case again, the exception for that column is fixed but it now complains about the next field which is "measurementUnit", and so on.
I am using spring boot starter version 2.7.1 and hibernate-core version 6.1.0.Final.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.0.Final</version>
</dependency>
Therefore, I followed this guide, for using the right naming strategy. My application.yml file for in the test package looks like this
cloud:
aws:
credentials:
access-key: myAccessKey
secret-key: mySecretKey
region:
static: us-west-2
spring:
autoconfigure:
exclude:
- io.awspring.cloud.autoconfigure.messaging.SnsAutoConfiguration
application:
name: My Application
liquibase:
contexts: test
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:h2:mem:tspservice;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL;
name:
username:
password:
hikari:
auto-commit: false
jpa:
database-platform: org.hibernate.dialect.H2Dialect
database: H2
open-in-view: false
show-sql: false
hibernate:
ddl-auto: none
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
properties:
hibernate.id.new_generator_mappings: true
hibernate.connection.provider_disables_autocommit: true
hibernate.cache.use_second_level_cache: false
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: false
hibernate.hbm2ddl.auto: validate
hibernate.jdbc.time_zone: UTC
multitenancy:
tenants:
datasource:
username: myservice
password: myservice
url: "jdbc:h2:mem:"
connectionProperties: ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL;INIT=create schema if not exists tspservice\;
minIdleConnections: 2
maxPoolSize: 8
And my main application.yml for the application looks like this
server:
port: 8088
servlet:
context-path: /api/myapp/services/myserv1
management:
endpoints:
web:
base-path: /manage
db:
name: ${RDS_DB_NAME:myservice}
username: ${RDS_USERNAME:root}
password: ${RDS_PASSWORD:root}
url: jdbc:mariadb://${RDS_HOSTNAME:localhost}:${RDS_PORT:3306}
properties: useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&createDatabaseIfNotExist=true&rewriteBatchedStatements=true&&allowPublicKeyRetrieval=true
spring:
application:
name: My Service
liquibase:
contexts: dev
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: ${db.url}/${db.name}?${db.properties}
username: ${db.username}
password: ${db.password}
hikari:
poolName: Hikari
auto-commit: false
data-source-properties:
cachePrepStmts: true
prepStmtCacheSize: 250
prepStmtCacheSqlLimit: 2048
useServerPrepStmts: true
max-lifetime: 600000 #10 min
jpa:
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
database: MYSQL
show-sql: true
hibernate:
ddl-auto: none
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
properties:
hibernate.id.new_generator_mappings: true
hibernate.connection.provider_disables_autocommit: true
hibernate.multiTenancy: SCHEMA
jackson:
default-property-inclusion: non_null
multitenancy:
tenants: tenant1,tenant2
datasource:
username: ${db.username}
password: ${db.password}
url: ${db.url}/
connectionProperties: ?${db.properties}
minIdleConnections: 2
maxPoolSize: 8
But still, I am getting the exceptions. It seems like somehow the naming configurations are not working.
And here is the detailed stack trace.
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:248)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$8(ClassBasedTestDescriptor.java:363)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:368)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$9(ClassBasedTestDescriptor.java:363)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:362)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:283)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:282)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:272)
at java.base/java.util.Optional.orElseGet(Optional.java:369)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:271)
at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$before$2(ClassBasedTestDescriptor.java:197)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:196)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:80)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:148)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/example/srm/internaltspservice/config/multitenancy/MultiTenancyJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [actualValueName] in table [session_actual_values]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:132)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
... 62 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [actualValueName] in table [session_actual_values]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:421)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)
... 77 more
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [actualValueName] in table [session_actual_values]
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateTable(AbstractSchemaValidator.java:144)
at org.hibernate.tool.schema.internal.GroupedSchemaValidatorImpl.validateTables(GroupedSchemaValidatorImpl.java:42)
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.performValidation(AbstractSchemaValidator.java:97)
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:76)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:204)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:85)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:335)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409)
... 81 more
What should I do to fix this?
Use CASE_INSENSITIVE_IDENTIFIERS=TRUE; When set to true, all identifier names (table names, column names) are case insensitive. Setting this to "true" is experimental.
add DATABASE_TO_UPPER=FALSE When set to true unquoted identifiers and short name of database are converted to upper case.
Another approach is to use the H2 logs:https://stackoverflow.com/a/72712120/4017037
I'm trying to integrate Javers 5.9.0 with my Spring Boot 2.1.13 application with mySQL.
As soon I run my application I'm getting
java.lang.RuntimeException: java.sql.SQLSyntaxErrorException:
Duplicate key name 'jv_global_id_owner_id_fk_idx'
Please find the full error stack
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'JaversFromStarter' defined in class path
resource
[org/javers/spring/boot/sql/JaversSqlAutoConfiguration.class]:
Invocation of init method failed; nested exception is
java.lang.RuntimeException: java.sql.SQLSyntaxErrorException:
Duplicate key name 'jv_global_id_owner_id_fk_idx' at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1771)
~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:847)
~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
~[spring-context-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
~[spring-context-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
~[spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE] at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744)
[spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE] at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391)
[spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
[spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
[spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1204)
[spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE] at
[classes/:na] Caused by: java.lang.RuntimeException:
java.sql.SQLSyntaxErrorException: Duplicate key name
'jv_global_id_owner_id_fk_idx' at
org.javers.repository.sql.schema.JaversSchemaManager.executeSQL(JaversSchemaManager.java:165)
~[javers-persistence-sql-5.9.0.jar:na] at
org.javers.repository.sql.schema.JaversSchemaManager.addIndex(JaversSchemaManager.java:343)
~[javers-persistence-sql-5.9.0.jar:na] at
org.javers.repository.sql.schema.JaversSchemaManager.addDbIndexOnOwnerId(JaversSchemaManager.java:102)
~[javers-persistence-sql-5.9.0.jar:na] at
org.javers.repository.sql.schema.JaversSchemaManager.ensureSchema(JaversSchemaManager.java:61)
~[javers-persistence-sql-5.9.0.jar:na] at
org.javers.repository.sql.JaversSqlRepository.ensureSchema(JaversSqlRepository.java:186)
~[javers-persistence-sql-5.9.0.jar:na] at
org.javers.spring.jpa.JaversTransactionalDecorator$1.doInTransactionWithoutResult(JaversTransactionalDecorator.java:186)
~[javers-spring-jpa-5.9.0.jar:na] at
org.springframework.transaction.support.TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:36)
~[spring-tx-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
~[spring-tx-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.javers.spring.jpa.JaversTransactionalDecorator.ensureSchema(JaversTransactionalDecorator.java:183)
~[javers-spring-jpa-5.9.0.jar:na] at
org.javers.spring.jpa.JaversTransactionalDecorator.afterPropertiesSet(JaversTransactionalDecorator.java:177)
~[javers-spring-jpa-5.9.0.jar:na] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1830)
~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1767)
~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE] ... 16 common
frames omitted Caused by: java.sql.SQLSyntaxErrorException: Duplicate
key name 'jv_global_id_owner_id_fk_idx' at
com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
~[mysql-connector-java-8.0.19.jar:8.0.19] at
com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
~[mysql-connector-java-8.0.19.jar:8.0.19] at
com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
~[mysql-connector-java-8.0.19.jar:8.0.19] at
com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:764)
~[mysql-connector-java-8.0.19.jar:8.0.19] at
com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648)
~[mysql-connector-java-8.0.19.jar:8.0.19] at
com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95)
~[HikariCP-3.2.0.jar:na] at
com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java)
~[HikariCP-3.2.0.jar:na] at
org.javers.repository.sql.schema.JaversSchemaManager.executeSQL(JaversSchemaManager.java:160)
~[javers-persistence-sql-5.9.0.jar:na] ... 27 common frames omitted
Found a work around
in application.yaml make following changes sqlSchemaManagementEnabled: false. This will stop creating tables at application start up
Create the table/indexes manually. Something like
CREATE TABLE javers.jv_commit ( commit_pk BIGINT NOT NULL
AUTO_INCREMENT, author VARCHAR(200), commit_date TIMESTAMP(3),
commit_date_instant VARCHAR(30), commit_id NUMERIC(22,2), CONSTRAINT
jv_commit_pk PRIMARY KEY(commit_pk) ) ENGINE = InnoDB;
CREATE INDEX jv_commit_commit_id_idx ON
gears_javers.jv_commit(commit_id)
CREATE TABLE javers.jv_commit_property ( property_name
VARCHAR(191) NOT NULL, property_value VARCHAR(600), commit_fk BIGINT,
CONSTRAINT jv_commit_property_pk PRIMARY KEY(commit_fk,
property_name), CONSTRAINT jv_commit_property_commit_fk FOREIGN
KEY(commit_fk) REFERENCES gears_javers.jv_commit(commit_pk) ) ENGINE =
InnoDB
CREATE INDEX jv_commit_property_commit_fk_idx ON
gears_javers.jv_commit_property(commit_fk) CREATE INDEX
jv_commit_property_property_name_property_value_idx ON
gears_javers.jv_commit_property(property_name,property_value(191))
CREATE TABLE javers.jv_global_id ( global_id_pk BIGINT NOT NULL
AUTO_INCREMENT, local_id VARCHAR(191), fragment VARCHAR(200),
type_name VARCHAR(200), owner_id_fk BIGINT, CONSTRAINT jv_global_id_pk
PRIMARY KEY(global_id_pk), CONSTRAINT jv_global_id_owner_id_fk FOREIGN
KEY(owner_id_fk) REFERENCES gears_javers.jv_global_id(global_id_pk) )
ENGINE = InnoDB
CREATE INDEX jv_global_id_local_id_idx ON
gears_javers.jv_global_id(local_id); CREATE INDEX
jv_global_id_owner_id_fk_idx ON
gears_javers.jv_global_id(owner_id_fk);
CREATE TABLE javers.jv_snapshot ( snapshot_pk BIGINT NOT NULL
AUTO_INCREMENT, type VARCHAR(200), version BIGINT, state TEXT,
changed_properties TEXT, managed_type VARCHAR(200), global_id_fk
BIGINT, commit_fk BIGINT, CONSTRAINT jv_snapshot_pk PRIMARY
KEY(snapshot_pk), CONSTRAINT jv_snapshot_global_id_fk FOREIGN
KEY(global_id_fk) REFERENCES gears_javers.jv_global_id(global_id_pk),
CONSTRAINT jv_snapshot_commit_fk FOREIGN KEY(commit_fk) REFERENCES
gears_javers.jv_commit(commit_pk) ) ENGINE = InnoDB
CREATE INDEX jv_snapshot_global_id_fk_idx ON
gears_javers.jv_snapshot(global_id_fk); CREATE INDEX
jv_snapshot_commit_fk_idx ON gears_javers.jv_snapshot(commit_fk);
CREATE INDEX jv_snapshot_owner_id_fk_idx ON
gears_javers.jv_global_id(owner_id_fk);
Try to reproduce the issue int this test https://github.com/javers/javers/blob/master/javers-persistence-sql/src/test/groovy/org/javers/repository/sql/integration/docker/MySqlDockerIntegrationTest.groovy Then we will fix it
I have a small problem. I'm trying to write a small Spring Boot Application and use Hibernate. This works as well as well, unfortunately I get the above mentioned error message when building <mvn clean package>. The error does not occur until the tests are started. Actually, it's also logical, Hibernate or JUnit tries to use 0000-00-00 00:00:00 as the test date. MySQL does not allow that. how can i tell the test to say `Now ()?
The Testclass:
package com.webservice.spring;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class ApiApplicationTests
{
#Test
public void contextLoads()
{
}
}
this is the definition in the model:
#NotNull
#Generated(value=GenerationTime.ALWAYS)
#Column(name = "lastchange", columnDefinition = "DATETIME", nullable = false)
private LocalDate lastchanged;
and a snippet of the StackTrace:
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '0000-00-00 00:00:00' for column 'lastchange' at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3971)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2483)
at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1552)
at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2607)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1480)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
at com.sun.proxy.$Proxy96.executeUpdate(Unknown Source)
at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:56)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlString(SchemaMigratorImpl.java:431)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlStrings(SchemaMigratorImpl.java:449)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.migrateTable(SchemaMigratorImpl.java:253)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:170)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:360)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:382)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
what can i do to prevent the test from failing?
You could do either of the following
Changing the default value for a column with an ALTER TABLE
statement, e.g.
ALTER TABLE users MODIFY created datetime NULL DEFAULT '1970-01-01'
Change the date column to allow NULL values, and update the existing
rows to change the zero dates to null values
The Answer:
in the Model Class:
#Column(name = "lastchange", columnDefinition = "DATETIME default '1900-01-01 00:00:00'", nullable = false)
private LocalDate lastchanged;
you can set the default in the Column Anotation