I have on spring boot app having one entity class which is linked to my database table also I used sequence on that table.
So I use Table annotation as well as SequenceGenerator annotation on my Entity class with hard-coded value, like this:
#Entity
#Primary
#Table(name = "tbl_name", schema = "public")
//#Table(name = "tbl_name_dev", schema = "public")
public class PoJoClass implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "tbl_name_id_seq", sequenceName = "tbl_name_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "tbl_name_id_seq")
// PoJo attributes
// Setter/Getter
}
Which I wanted to implement in way where I can set both the table and sequence as parameter for each profile like dev and prod. As for testing we have table name different then prod in some cases.
Also, I used the same table name in my repository class with #Query annotation, which look like this:
#Query(value = "SELECT * FROM tbl_name WHERE col1 <> ?1", nativeQuery = true)
PoJoClass getLatestRecordForCompositeKey(String col1);
Finding out same way to set both as parameter on each profile base.
Update:
Alex, route me to follow this link. And I checked and tried implementing the same in my code but I might not understand that logic due to that it is failing or nothing which I did not get properly. Cloud anyone please help on this.
I wanted to use property: from my application property file and i added the same there.
As that link suggested added the Configuration class.
#Configuration
public class TableNameConfig {
#Value("${config.table.name}")
private String configTableName;
#Value("${visits.table.name}")
private String visitsTableName;
#Bean
public PhysicalNamingStrategyStandardImpl physicalNamingStrategyStandard(){
return new PhysicalNamingImpl();
}
class PhysicalNamingImpl extends PhysicalNamingStrategyStandardImpl {
#Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
switch (name.getText()) {
case "PoJoClass":
return new Identifier(configTableName, name.isQuoted());
case "Visits":
return new Identifier(visitsTableName, name.isQuoted());
case "Result":
default:
return super.toPhysicalTableName(name, context);
}
}
}
}
So that I can later use the property like this:
#Table(name = "${config.table.name}", schema = "public")
But I am getting this error, I think I am not able to resolve that property, not understood where to change and what:
2019-12-07 15:57:46.649 INFO 21840 --- [ restartedMain]
org.hibernate.type.BasicTypeRegistry : HHH000270: Type
registration [java.util.UUID] overrides previous :
org.hibernate.type.UUIDBinaryType#233cf9c7 Hibernate: create table
public.${config.table.name} (id serial not null, active_flag
varchar(255), updated_datetime TIMESTAMP WITHOUT TIME ZONE, primary
key (id))
2019-12-07 15:57:50.561 WARN 21840 --- [ restartedMain]
o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget
encountered exception accepting command : Error executing DDL "create
table public.${config.table.name} (id serial not null, active_flag
varchar(255), updated_datetime TIMESTAMP WITHOUT TIME ZONE, primary
key (id))" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error
executing DDL "create table public.${config.table.name} (id serial not
null, active_flag varchar(255), updated_datetime TIMESTAMP WITHOUT
TIME ZONE, primary key (id))" via JDBC Statement at
org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:277)
[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:71)
[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:207)
[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183)
[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:310)
[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467)
[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939)
[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390)
[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377)
[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837)
[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774)
[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105)
~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE] at
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE] at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:743)
~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE] at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:390)
~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1214)
~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1203)
~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE] at
com.slb.dataplatform.configurationapi.ConfigurationApiApplication.main(ConfigurationApiApplication.java:12)
~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) ~[na:1.8.0_201] at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
~[na:1.8.0_201] at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[na:1.8.0_201] at java.lang.reflect.Method.invoke(Method.java:498)
~[na:1.8.0_201] at
org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
~[spring-boot-devtools-2.1.7.RELEASE.jar:2.1.7.RELEASE] Caused by:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$"
Position: 21 at
org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2476)
~[postgresql-42.1.1.jar:42.1.1] at
org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2189)
~[postgresql-42.1.1.jar:42.1.1] at
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
~[postgresql-42.1.1.jar:42.1.1] at
org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428)
~[postgresql-42.1.1.jar:42.1.1] at
org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354)
~[postgresql-42.1.1.jar:42.1.1] at
org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:301)
~[postgresql-42.1.1.jar:42.1.1] at
org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:287)
~[postgresql-42.1.1.jar:42.1.1] at
org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:264)
~[postgresql-42.1.1.jar:42.1.1] at
org.postgresql.jdbc.PgStatement.execute(PgStatement.java:260)
~[postgresql-42.1.1.jar:42.1.1] 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.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] ... 39 common frames
omitted
I think I am not able to override method toPhysicalTableName properly, please let me know what is wrong I did.
Help is highly appreciated. thanks in advance.
Related
I use R2DBC MySQL driver in my Spring Webflux reactive web. And I try to execute table schema SQL script. But the script continuously cause errors.
First, I make 3 model classes.
User.java
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Table("blog_user")
public class User {
#Id
#Column("user_id")
private Long id;
#Column
private String username;
#Column
#JsonIgnore
private String password;
#Column
private String fullname;
#Column
private Integer role;
}
Post.java
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Table
public class Post {
#Id
#Column("post_id")
private Long id;
#Column
private String title;
#Column
private String body;
#Column("created_date")
private LocalDateTime createdDate;
#Column("user_id")
private User user;
#Column("posts")
private Collection<Tag> tags;
}
Tag.java
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
#Table
public class Tag {
#Id
#Column("tag_id")
private Long id;
#Column
private String body;
#Column("created_date")
private LocalDateTime createdDate;
#Column("post_id")
private Post post;
#Column("user_id")
private User user;
}
schema.sql
-- TABLE intialized.
DROP TABLE IF EXISTS tag;
DROP TABLE IF EXISTS post;
DROP TABLE IF EXISTS blog_user;
-- TABLE created.
CREATE TABLE IF NOT EXISTS blog_user (
user_id BIGINT NOT NULL,
username VARCHAR(30) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255),
fullname VARCHAR(255),
role SMALLINT CHECK (role IN (0, 1)),
PRIMARY KEY (user_id),
UNIQUE (username)
);
CREATE TABLE IF NOT EXISTS post (
post_id BIGINT NOT NULL,
title VARCHAR(30) NOT NULL,
body TEXT,
created_date DATETIME(6) NOT NULL,
user_id BIGINT NOT NULL,
PRIMARY KEY (post_id),
FOREIGN KEY (user_id) REFERENCES blog_user (user_id)
);
CREATE TABLE IF NOT EXISTS tag(
tag_id BIGINT NOT NULL,
body VARCHAR(255),
created_date DATETIME(6) NOT NULL,
post_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
PRIMARY KEY (tag_id),
FOREIGN KEY (post_id) REFERENCES post (post_id),
FOREIGN KEY (user_id) REFERENCES blog_user (user_id)
);
Below configuration method executes schema.sql.
reactive web initializer method
#Bean
ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory) {
ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();
initializer.setConnectionFactory(connectionFactory);
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScripts(new ClassPathResource(schema.sql));
initializer.setDatabasePopulator(databasePopulator);
return initializer;
}
However, initially executed schema.sql throws errors,
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
[2m2023-01-01T09:06:30.943+09:00[0;39m [33m WARN[0;39m [35m10464[0;39m [2m---[0;39m [2m[actor-tcp-nio-3][0;39m [36mdev.miku.r2dbc.mysql.MySqlConnection [0;39m [2m:[0;39m The server timezone is <???ѹα? ǥ?ؽ> that's unknown, trying to use system default timezone
[2m2023-01-01T09:06:30.945+09:00[0;39m [33m WARN[0;39m [35m10464[0;39m [2m---[0;39m [2m[actor-tcp-nio-3][0;39m [36mdev.miku.r2dbc.mysql.MySqlConnection [0;39m [2m:[0;39m The server timezone is <???ѹα? ǥ?ؽ> that's unknown, trying to use system default timezone
[2m2023-01-01T09:06:30.947+09:00[0;39m [33m WARN[0;39m [35m10464[0;39m [2m---[0;39m [2m[actor-tcp-nio-3][0;39m [36mdev.miku.r2dbc.mysql.MySqlConnection [0;39m [2m:[0;39m The server timezone is <???ѹα? ǥ?ؽ> that's unknown, trying to use system default timezone
[2m2023-01-01T09:06:30.948+09:00[0;39m [33m WARN[0;39m [35m10464[0;39m [2m---[0;39m [2m[actor-tcp-nio-3][0;39m [36mdev.miku.r2dbc.mysql.MySqlConnection [0;39m [2m:[0;39m The server timezone is <???ѹα? ǥ?ؽ> that's unknown, trying to use system default timezone
[2m2023-01-01T09:06:30.951+09:00[0;39m [33m WARN[0;39m [35m10464[0;39m [2m---[0;39m [2m[actor-tcp-nio-3][0;39m [36mdev.miku.r2dbc.mysql.MySqlConnection [0;39m [2m:[0;39m The server timezone is <???ѹα? ǥ?ؽ> that's unknown, trying to use system default timezone
[2m2023-01-01T09:06:30.953+09:00[0;39m [33m WARN[0;39m [35m10464[0;39m [2m---[0;39m [2m[actor-tcp-nio-3][0;39m [36mdev.miku.r2dbc.mysql.MySqlConnection [0;39m [2m:[0;39m The server timezone is <???ѹα? ǥ?ؽ> that's unknown, trying to use system default timezone
[2m2023-01-01T09:06:30.955+09:00[0;39m [33m WARN[0;39m [35m10464[0;39m [2m---[0;39m [2m[actor-tcp-nio-3][0;39m [36mdev.miku.r2dbc.mysql.MySqlConnection [0;39m [2m:[0;39m The server timezone is <???ѹα? ǥ?ؽ> that's unknown, trying to use system default timezone
[2m2023-01-01T09:06:30.974+09:00[0;39m [31mERROR[0;39m [35m10464[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mo.s.boot.SpringApplication [0;39m [2m:[0;39m Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'initializer' defined in class path resource [com/aaa/blog/wf/config/BlogWebFluxConfig.class]: Failed to execute SQL script statement #1 of class path resource [sql/spring-boot-mysql-schema.sql]: DROP TABLE IF EXISTS tag
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1751) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:599) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:961) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:915) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:66) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291) ~[spring-boot-3.0.1.jar:3.0.1]
at com.aaa.blog.wf.SpringBlogWebFluxMySqlApplication.main(SpringBlogWebFluxMySqlApplication.java:10) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-3.0.1.jar:3.0.1]
Caused by: org.springframework.r2dbc.connection.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of class path resource [sql/spring-boot-mysql-schema.sql]: DROP TABLE IF EXISTS tag
at org.springframework.r2dbc.connection.init.ScriptUtils.lambda$runStatement$9(ScriptUtils.java:571) ~[spring-r2dbc-6.0.3.jar:6.0.3]
at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:94) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.MonoStreamCollector$StreamCollectorSubscriber.onError(MonoStreamCollector.java:149) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.MonoStreamCollector$StreamCollectorSubscriber.onNext(MonoStreamCollector.java:126) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxFlatMap$FlatMapMain.tryEmit(FluxFlatMap.java:543) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxFlatMap$FlatMapInner.onNext(FluxFlatMap.java:984) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:122) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxPeek$PeekSubscriber.onNext(FluxPeek.java:200) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1839) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.NextProcessor.tryEmitValue(NextProcessor.java:358) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.NextProcessor.onNext(NextProcessor.java:298) ~[reactor-core-3.5.1.jar:3.5.1]
at dev.miku.r2dbc.mysql.MySqlResult.lambda$null$3(MySqlResult.java:114) ~[r2dbc-mysql-0.8.2.RELEASE.jar:0.8.2.RELEASE]
at reactor.core.publisher.LambdaSubscriber.onNext(LambdaSubscriber.java:160) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxWindowPredicate$WindowFlux.drainRegular(FluxWindowPredicate.java:670) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxWindowPredicate$WindowFlux.drain(FluxWindowPredicate.java:748) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxWindowPredicate$WindowFlux.onNext(FluxWindowPredicate.java:790) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxWindowPredicate$WindowPredicateMain.onNext(FluxWindowPredicate.java:241) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxHandleFuseable$HandleFuseableSubscriber.onNext(FluxHandleFuseable.java:193) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxContextWrite$ContextWriteSubscriber.onNext(FluxContextWrite.java:107) ~[reactor-core-3.5.1.jar:3.5.1]
at dev.miku.r2dbc.mysql.util.DiscardOnCancelSubscriber.onNext(DiscardOnCancelSubscriber.java:70) ~[r2dbc-mysql-0.8.2.RELEASE.jar:0.8.2.RELEASE]
at reactor.core.publisher.FluxPeekFuseable$PeekConditionalSubscriber.onNext(FluxPeekFuseable.java:854) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.MonoFlatMapMany$FlatMapManyInner.onNext(MonoFlatMapMany.java:250) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxPeek$PeekSubscriber.onNext(FluxPeek.java:200) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxHandle$HandleSubscriber.onNext(FluxHandle.java:128) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.FluxPeekFuseable$PeekConditionalSubscriber.onNext(FluxPeekFuseable.java:854) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.EmitterProcessor.drain(EmitterProcessor.java:537) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.EmitterProcessor.tryEmitNext(EmitterProcessor.java:343) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.InternalManySink.emitNext(InternalManySink.java:27) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.EmitterProcessor.onNext(EmitterProcessor.java:309) ~[reactor-core-3.5.1.jar:3.5.1]
at dev.miku.r2dbc.mysql.client.ReactorNettyClient$ResponseSink.next(ReactorNettyClient.java:340) ~[r2dbc-mysql-0.8.2.RELEASE.jar:0.8.2.RELEASE]
at dev.miku.r2dbc.mysql.client.ReactorNettyClient.lambda$new$0(ReactorNettyClient.java:103) ~[r2dbc-mysql-0.8.2.RELEASE.jar:0.8.2.RELEASE]
at reactor.core.publisher.FluxPeek$PeekSubscriber.onNext(FluxPeek.java:185) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.netty.channel.FluxReceive.drainReceiver(FluxReceive.java:292) ~[reactor-netty-core-1.1.1.jar:1.1.1]
at reactor.netty.channel.FluxReceive.onInboundNext(FluxReceive.java:401) ~[reactor-netty-core-1.1.1.jar:1.1.1]
at reactor.netty.channel.ChannelOperations.onInboundNext(ChannelOperations.java:411) ~[reactor-netty-core-1.1.1.jar:1.1.1]
at reactor.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:113) ~[reactor-netty-core-1.1.1.jar:1.1.1]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at dev.miku.r2dbc.mysql.client.MessageDuplexCodec.handleDecoded(MessageDuplexCodec.java:187) ~[r2dbc-mysql-0.8.2.RELEASE.jar:0.8.2.RELEASE]
at dev.miku.r2dbc.mysql.client.MessageDuplexCodec.channelRead(MessageDuplexCodec.java:95) ~[r2dbc-mysql-0.8.2.RELEASE.jar:0.8.2.RELEASE]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:442) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:346) ~[netty-codec-4.1.86.Final.jar:4.1.86.Final]
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:318) ~[netty-codec-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1373) ~[netty-handler-4.1.86.Final.jar:4.1.86.Final]
at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1236) ~[netty-handler-4.1.86.Final.jar:4.1.86.Final]
at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1285) ~[netty-handler-4.1.86.Final.jar:4.1.86.Final]
at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:529) ~[netty-codec-4.1.86.Final.jar:4.1.86.Final]
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:468) ~[netty-codec-4.1.86.Final.jar:4.1.86.Final]
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:290) ~[netty-codec-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:440) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:788) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562) ~[netty-transport-4.1.86.Final.jar:4.1.86.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) ~[netty-common-4.1.86.Final.jar:4.1.86.Final]
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.86.Final.jar:4.1.86.Final]
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.86.Final.jar:4.1.86.Final]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
Suppressed: java.lang.Exception: #block terminated with an error
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99) ~[reactor-core-3.5.1.jar:3.5.1]
at reactor.core.publisher.Mono.block(Mono.java:1710) ~[reactor-core-3.5.1.jar:3.5.1]
at org.springframework.r2dbc.connection.init.ConnectionFactoryInitializer.execute(ConnectionFactoryInitializer.java:112) ~[spring-r2dbc-6.0.3.jar:6.0.3]
at org.springframework.r2dbc.connection.init.ConnectionFactoryInitializer.afterPropertiesSet(ConnectionFactoryInitializer.java:97) ~[spring-r2dbc-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1797) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1747) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:599) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:961) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:915) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:66) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291) ~[spring-boot-3.0.1.jar:3.0.1]
at com.aaa.blog.wf.SpringBlogWebFluxMySqlApplication.main(SpringBlogWebFluxMySqlApplication.java:10) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-3.0.1.jar:3.0.1]
Caused by: java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long (java.lang.Integer and java.lang.Long are in module java.base of loader 'bootstrap')
at java.base/java.util.stream.Collectors.lambda$summingLong$23(Collectors.java:699) ~[na:na]
at reactor.core.publisher.MonoStreamCollector$StreamCollectorSubscriber.onNext(MonoStreamCollector.java:117) ~[reactor-core-3.5.1.jar:3.5.1]
... 67 common frames omitted
I think my reactive R2DBC model classes contains some errors. ClassCastException. But I have no idea what element has wrong class type. The printed error message show no code line number. I changed the id type of model class(User, Post, Tag) into Integer type, but the same errors are thrown.
If you are using https://github.com/mirromutth/r2dbc-mysql 0.8.x RELEASE and the latest Spring Boot 2.7 or Spring Boot 3.0.x, I think there is a compatibility issue between the R2dbc MySQL driver you are using and R2dbc SPI managed by Spring Boot.
In the latest Spring Boot 3.0, R2dbc SPI was updated to 1.0, which introduced several incompatible APIs since 0.8(r2dbc-mysql 0.8.x RELEASE is aligned with R2dbc SPI 0.8). I have encountered similar exceptions when upgrading to R2dbc 0.9 and 1.0 but used driver version is incompatible.
Try to use the latest MariaDB R2dbc Driver to connect your MySQL
Consider other database, eg. PostgreSQL or switch to MariaDB directly.
Helped for me change dependency from
implementation("org.postgresql:r2dbc-postgresql:1.0.0.RELEASE")
to
implementation("io.r2dbc:r2dbc-postgresql:0.8.13.RELEASE")
for springboot 2.7.6
Thanks to Hantsy.
I recently upgraded my Spring Boot version from v2.2.4.RELEASE to v2.2.6.RELEASE, thereby upgrading the Hibernate and Hibernate Envers version from 5.4.10.Final to 5.4.12.Final.
The exception
When I start the application now, I get an exception from the schema validation as shown below:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.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: wrong column type encountered in column [password] in table [users_aud]; found [binary (Types#BINARY)], but expecting [varchar(255) (Types#VARCHAR)]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$276/0000000000000000.getObject(Unknown Source) ~[na:na]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:330) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
... 117 common frames omitted
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [password] in table [users_aud]; found [binary (Types#BINARY)], but expecting [varchar(255) (Types#VARCHAR)]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:403) ~[spring-orm-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) ~[spring-orm-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
... 125 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [password] in table [users_aud]; found [binary (Types#BINARY)], but expecting [varchar(255) (Types#VARCHAR)]
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateColumnType(AbstractSchemaValidator.java:159) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateTable(AbstractSchemaValidator.java:143) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.tool.schema.internal.GroupedSchemaValidatorImpl.validateTables(GroupedSchemaValidatorImpl.java:42) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.performValidation(AbstractSchemaValidator.java:89) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:68) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:192) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:314) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1237) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.5.RELEASE.jar:5.2.5.RELEASE]
... 129 common frames omitted
The DDL statements
Apparently, Hibernate expects a column type in the aud table different than the column type from the original table. I created the tables as follows (other columns left out for brevity):
create table users
(
password binary(60) not null,
) engine = InnoDB;
create table users_aud
(
id bigint not null,
rev integer not null,
revtype tinyint,
revend integer,
password binary(60),
password_mod bit,
primary key (id, rev)
) engine = InnoDB;
The Entity in Java
The User entity in Java (other fields and equals/hashCode left out for brevity):
#Entity
#Audited
#Inheritance(strategy = InheritanceType.JOINED)
#NoArgsConstructor
#Getter
#Table(name = "users")
public abstract class User extends HasId implements UserDetails {
#Column(columnDefinition = "BINARY(60)", nullable = false)
private String password;
}
The Hibernate config
My Hibernate config looks as follows (application.yml for Spring Boot):
spring:
jpa:
hibernate:
ddl-auto: validate
properties:
hibernate:
connection:
provider_disables_autocommit: true
dialect: org.hibernate.dialect.MySQL57Dialect
implicit_naming_strategy: component-path
jdbc:
time_zone: UTC
order_inserts: true
order_updates: true
org:
hibernate:
envers:
audit_strategy: org.hibernate.envers.strategy.ValidityAuditStrategy
global_with_modified_flag: true
Final notes
The strange thing is that it worked perfectly until the version upgrade. Unfortunately, I can't find anything related to this issue in the 5.4.11 or 5.4.12 release notes except for maybe this one. The database is MySQL version 5.7.
I have a spring-boot application that defines a mysql DataSource:
spring.datasource.url=...
spring.datasource.username=...
spring.datasource.password=...
I run the tool as command line application triggered by a cronjob. And in 80% of all runs, I could exit the tool without having to contact the database at all:
#Controller
public class MainController {
#Autowired
private MyService myService;
public void evaluate() {
if (condition == true) myService.run();
else System.exit(0);
}
}
#Service
#Lazy
public class MyService {
#Autowired
private JdbcTemplate jdbc;
public void run() {
jdbc.execute(sql);
}
}
Problem: I want to prevent spring initializing the database at all. So, if for example the database is down or the host is unreachable (could be tested with using spring.datasource.url=localhostX), then the tool should still be runable.
Is that possible to delay the datasource initialization until it is really needed?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744) ~[spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391) ~[spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) ~[spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204) ~[spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:179) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) ~[spring-orm-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.10.RELEASE.jar:5.1.10.RELEASE]
... 15 common frames omitted
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.3.12.Final.jar:5.3.12.Final]
... 32 common frames omitted
#SpringBootApplication(exclude = HibernateJpaAutoConfiguration.class)
Somehow the hikari pool and hibernate seem to interact on startup. And if the datasource is not present, startup fails.
Using the exclusion above with #Lazy annotation delays the initialization as expected.
But that only works because I don't make use of hibernate.
As said in spring doc(https://docs.spring.io/spring-boot/docs/2.1.13.RELEASE/reference/html/boot-features-sql.html):
Spring Data JPA repositories support three different modes of bootstrapping: default, deferred, and lazy. To enable deferred or lazy bootstrapping, set the spring.data.jpa.repositories.bootstrap-mode to deferred or lazy respectively.
So try the following config in your application.properties (or yaml):
spring.data.jpa.repositories.bootstrap-mode=lazy
Starting with Springboot 2.2 it is possible.
Add the following property in application.properties
spring.main.lazy-initialization=true
Read more detail here.
When using Hibernate as JPA implementation, I was able to avoid connecting to database during application startup by setting these 2 hibernate specific properties even though the beans are initialised at startup -
spring:
jpa:
properties:
hibernate:
temp:
use_jdbc_metadata_defaults: false
hbm2ddl:
auto: none
Here are the significance of these properties from Hibernate Documentation
hibernate.temp.use_jdbc_metadata_defaults (e.g. true (default value)
or false)
This setting is used to control whether we should consult
the JDBC metadata to determine certain Settings default values when
the database may not be available (mainly in tools usage).
and here
hibernate.hbm2ddl.auto (e.g. none (default value), create-only, drop,
create, create-drop, validate, and update)
Setting to perform
SchemaManagementTool actions automatically as part of the
SessionFactory lifecycle. Valid options are defined by the
externalHbm2ddlName value of the Action enum:
none No action will be performed.
So, after setting the properties, the jdbc connection is made only when executing sql queries.
I have been using H2 as the database in my app, which is dropping all the data when app is terminated. Now I would like to use database, which persist all the data to files on my disk.
I have chosen MariaDB for this, but MariaDB can't create one of my tables (every entity gets created except one). Since I had no problems using H2 I assume it is something with my configuration.
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>com.h2database</groupId>-->
<!--<artifactId>h2</artifactId>-->
<!--<scope>runtime</scope>-->
<!--</dependency>-->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>1.5.7</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
</dependencies>
application.properties
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=springuser
#spring.h2.console.enabled=true
Entity that won't be created (using H2 there is no problem)
#Entity
#Table(name = "MEETINGS")
public class Meeting extends BaseEntity {
private Date when;
private String topic;
#ManyToOne
#JoinColumn(name = "CLIENT_ID", nullable = false)
private Client client;
#ManyToOne
#JoinColumn(name = "ESTATE_ID", nullable = false)
private Estate estate;
Exception
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:375) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:312) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892) [hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) [spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) [spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) [spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1758) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1695) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:573) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:859) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at pl.isbd.estate.dealer.Application.main(Application.java:13) ~[classes/:na]
Caused by: java.sql.SQLSyntaxErrorException: (conn:174) Table 'db_example.meetings' doesn't exist
Query is : alter table meetings add constraint FK5lfl8h6qtwn2ut7mkblahc46s foreign key (estate_id) references estates (id)
at org.mariadb.jdbc.internal.util.ExceptionMapper.get(ExceptionMapper.java:139) ~[mariadb-java-client-1.5.7.jar:na]
at org.mariadb.jdbc.internal.util.ExceptionMapper.getException(ExceptionMapper.java:101) ~[mariadb-java-client-1.5.7.jar:na]
at org.mariadb.jdbc.internal.util.ExceptionMapper.throwAndLogException(ExceptionMapper.java:77) ~[mariadb-java-client-1.5.7.jar:na]
at org.mariadb.jdbc.MariaDbStatement.executeQueryEpilog(MariaDbStatement.java:224) ~[mariadb-java-client-1.5.7.jar:na]
at org.mariadb.jdbc.MariaDbStatement.executeInternal(MariaDbStatement.java:253) ~[mariadb-java-client-1.5.7.jar:na]
at org.mariadb.jdbc.MariaDbStatement.execute(MariaDbStatement.java:266) ~[mariadb-java-client-1.5.7.jar:na]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95) ~[HikariCP-2.7.9.jar:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-2.7.9.jar:na]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
... 34 common frames omitted
Caused by: org.mariadb.jdbc.internal.util.dao.QueryException: Table 'db_example.meetings' doesn't exist
Query is : alter table meetings add constraint FK5lfl8h6qtwn2ut7mkblahc46s foreign key (estate_id) references estates (id)
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.readErrorPacket(AbstractQueryProtocol.java:1098) ~[mariadb-java-client-1.5.7.jar:na]
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.readPacket(AbstractQueryProtocol.java:1030) ~[mariadb-java-client-1.5.7.jar:na]
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.getResult(AbstractQueryProtocol.java:985) ~[mariadb-java-client-1.5.7.jar:na]
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.executeQuery(AbstractQueryProtocol.java:129) ~[mariadb-java-client-1.5.7.jar:na]
at org.mariadb.jdbc.MariaDbStatement.executeInternal(MariaDbStatement.java:243) ~[mariadb-java-client-1.5.7.jar:na]
... 38 common frames omitted
You have a field named when which is probably causing a syntax error when it's trying to create the table. Either rename that field or use the #Column annotation to specify a column name that is allowed.
For future readers, in my case, there were no exceptions to figure it out. The issue comes from columnDefinition attribute below :
#Column(name="service_id", columnDefinition="NULL", length = 11)
private Integer serviceId;
I had to get rid of columnDefinition="NULL" as long as this attribute overrides the DDL definition and produced in my case a wrong column definition : service_id NULL (as it removes the data type definition (int)) in table's DDL generated creation code.
I want to add a connection pool to my existing web application, which has been made using Spring Boot 1.5.1.
The datasource configuration is made in application.properties as follows:
spring.datasource.url=jdbc:jtds:sqlserver://localhost:1433;databaseName=MyDatabase;instance=SQLServer2014;
spring.datasource.username=myuser
spring.datasource.password=passwd
spring.datasource.driver-class-name=net.sourceforge.jtds.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
I don't need to make any further configuration, with this is enough.
It isn't clear enough in the official docs, although parameters are shown, nor in the Spring Boot docs.
So, I've been looking for solutions over there (this one, this one too...).
I've made several trials, but everytime I run the app, exceptions regarding HikariCP are thrown.
When adding spring.datasource.type=com.zaxxer.hikari.HikariDataSource, the following exception is thrown:
2017-02-15 12:12:23.955 WARN 14844 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
2017-02-15 12:12:23.964 INFO 14844 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-02-15 12:12:23.970 ERROR 14844 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at com.ingartek.ws.pps.PrestacionesPoliticasSocialesInternoApplication.main(PrestacionesPoliticasSocialesInternoApplication.java:26) [classes/:na]
Caused by: java.lang.AbstractMethodError: null
at net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833) ~[jtds-1.3.1.jar:1.3.1]
at com.zaxxer.hikari.pool.PoolBase.checkDriverSupport(PoolBase.java:422) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.PoolBase.setupConnection(PoolBase.java:393) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:351) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:196) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:442) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:505) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:113) ~[HikariCP-2.6.0.jar:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:97) ~[HikariCP-2.6.0.jar:na]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:257) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885) ~[hibernate-core-5.2.6.Final.jar:5.2.6.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:362) ~[spring-orm-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
... 16 common frames omitted
So, which is the simplest way to add hikaricp to my application.properties?
You are getting below error.
Caused by: java.lang.AbstractMethodError: null at net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833)
Issue is that net.sourceforge.jtds.jdbc.JtdsConnection doesn't implement isValid so you need to specify a connection-test-query to ensure that isValid method isn't called. Try by adding below property in your application.properties file.
spring.datasource.hikari.connection-test-query=SELECT 1
For using multiple datasources (Spring Boot 2.0), I had to do the following to get this to work (setting spring.datasource.hikari.connection-test-query property only worked when using a single datasource):
#Configuration
public class DataConfig {
#Bean
#Primary
#ConfigurationProperties(prefix="spring.datasource")
public DataSource primaryDataSource() {
HikariDataSource ds = (HikariDataSource) DataSourceBuilder.create().build();
ds.setConnectionTestQuery("SELECT 1");
return ds;
}
#Bean(name="secondDataSource")
#ConfigurationProperties(prefix="spring.datasource.second")
public DataSource secondDataSource() {
HikariDataSource ds = (HikariDataSource) DataSourceBuilder.create().build();
ds.setConnectionTestQuery("SELECT 1");
return ds;
}
#Bean(name="primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(DataSource primaryDataSource) {
return new JdbcTemplate(primaryDataSource);
}
#Bean(name="secondJdbcTemplate")
public JdbcTemplate secondJdbcTemplate(#Qualifier("secondDataSource") DataSource secondDataSource) {
return new JdbcTemplate(secondDataSource);
}
}
I ran into the same problem and found the solution from this discussion.
It looks like, before doing any further configurations Hikari CP tests the validity of the connection by executing a test query which is missing in this case.
So as suggested by the earlier answer, you should add one test query in your application.properties file.
If you are using Oracle or mySql then you can use the following query instead (as SELECT 1 doesn't work here):
spring.datasource.hikari.connection-test-query=SELECT 1 FROM DUAL
Note: DUAL is a special one-row and one-column table present in Oracle and other databases. Thus it can be readily used to execute a simple test-query.