Spring Boot - multiple datasource - hbm2ddl issue - java

I have multiple datasources defined in my Spring Boot (version 2.1.3.Final) app, and for one of these I am setting hbm2ddl to update. However, if I ran the application for the second time, it always tries to execute CREATE TABLE statement (instead of alter, or no statement in case of no change in entity)
The datasource definition look like this:
// #formatter:off
#EnableJpaRepositories(entityManagerFactoryRef = "triggerEMF", transactionManagerRef = "triggerTM", basePackages = {
"com.customer.trigger.repository" }, excludeFilters = #Filter(CDHRepository.class))
// #formatter:on
#Configuration
#EnableTransactionManagement
public class TriggerDSConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(TriggerDSConfig.class);
#Autowired
private Environment env;
#Primary
#Bean(name = "triggerDS")
#ConfigurationProperties("trigger.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "triggerTM")
public PlatformTransactionManager psqlTransactionManager(#Qualifier("triggerEMF") EntityManagerFactory customerEntityManagerFactory) {
return new JpaTransactionManager(customerEntityManagerFactory);
}
#Primary
#Bean(name = "triggerEMF")
public LocalContainerEntityManagerFactoryBean psqlEntityManager(EntityManagerFactoryBuilder builder) throws SQLException {
Map<String, String> props = new HashMap<String, String>();
props.put("hibernate.hbm2ddl.auto", env.getProperty("trigger.hbm2ddl"));
props.put("hibernate.dialect", env.getProperty("trigger.dialect"));
props.put("hibernate.default_schema", "public");
DataSource ds = dataSource();
ds.getConnection(); // eager connection pool init
return builder.dataSource(ds) //
.packages("com.customer.trigger.model.entity") //
.persistenceUnit("trigger-pu") //
.properties(props) //
.build(); //
}
// Initialise & Populate DS in Local profile
#Bean
#Profile({ "local" })
public DataSourceInitializer triggerEngineDBInit(#Qualifier("triggerDS") DataSource datasource) {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("db/schema-triggerengine.sql"));
resourceDatabasePopulator.addScript(new ClassPathResource("db/data-triggerengine.sql"));
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(datasource);
dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
dataSourceInitializer.setEnabled(env.getProperty("trigger.datasource.initialize", Boolean.class, false));
return dataSourceInitializer;
}
}
The YAML definition of this datasource look like this:
trigger:
datasource:
jdbcUrl: jdbc:h2:~/triggerdb2;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL
username: sa
password: sa
hbm2ddl: update
dialect: org.hibernate.dialect.H2Dialect
I can confirm that DDL scripts are not executed. It's hbm2ddl which is failing. I was debugging it quite deep and I've got as far as this class:
https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/GroupedSchemaMigratorImpl.java
And this is the problematic piece of code:
https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/GroupedSchemaMigratorImpl.java#L69-L71
The table information is null - so hibernate generate create table statement (instead of alter or no statement). But of course the table exists, so this fails with following error:
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:277)
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:71)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:207)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:310)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1821)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1758)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at com.customer.trigger.Application.main(Application.java:11)
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.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:558)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.h2.jdbc.JdbcSQLException: Table "SUGGESTION_VOD__C" already exists; SQL statement:
This issue occurs with PostgreSQL as well (not just H2)
Any ideas?
Reproducer:
https://github.com/agiertli/spring-boot-hbm-ddl-issue

I ran your project in my local. you are correct when I ran twice I got the table already exist error. and solution was
Map<String, String> props = new HashMap<String, String>();
props.put("hibernate.hbm2ddl.auto", "update");
props.put("hibernate.dialect", env.getProperty("trigger.dialect"));
props.put("hibernate.default_schema", env.getProperty("trigger.schema"));
you are maybe missing some property in your yml. Also use #Value for these properties.

After removing following yaml configuration:
# temp:
# use_jdbc_metadata_defaults: "false"
The issue no longer occurs. Of course, now we are receiving strange CLOB related errors, but they do not seem to have a real impact so that's a separate issue.

i read your problem. the problem is not depend on database and I think your problem is that you don't use database version control for your project.
the version control handle the all of these things for you and(it knows when to create or alter and very much more).
these are good database version control that you can use
liquibase
flyway
my opinion is to use liquibase because its easier with very good documentation

Related

Spring Boot JPA - Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not working in JAVA 8u291

I'm running this on my local laptop and it seems work fine, but every time I tried to run on different server this following error appears. (Both using Java 8u291)
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaEntityManagerFactory' defined in class path resource [com/reclassification/HibernateConfiguration.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:1762)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at com.reclassification.ReclassificationApplication.main(ReclassificationApplication.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
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)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.(InFlightMetadataCollectorImpl.java:179)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1821)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1758)
... 24 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)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
Are you missing application.properties on different server?
From trace:
Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set at
Also check:answer about no dialect
Might be that the other server can't connect to DB.
The error "Access to DialectResolutionInfo cannot be null" seems very generic. In my case the cause was trying to connect to multiple databases in the same Spring Boot API.
In my case to resolve it, for Spring Boot 2.5.4, this example from Baeldung was helpful, and this from Medium as well.
Here is the application.yml file with dialect specified for MySQL db:
spring:
datasource:
primaryDB:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:<port>/<primary db name>?charSet=LATIN1
username: <username>
password: <password>
initialization-mode: always
otherDB:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:<port>/<other db name>?charSet=LATIN1
username: <username>
password: <password>
initialization-mode: always
jpa:
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
With #Configuration class for the primary db:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory",
basePackages = { "com.foo.bar.repository" }
)
public class PrimaryDBConfig {
#Value("${spring.datasource.primaryDB.driverClassName}")
private String driver;
#Value("${spring.datasource.primaryDB.url}")
private String url;
#Value("${spring.datasource.primaryDB.username}")
private String username;
#Value("${spring.datasource.primaryDB.password}")
private String password;
#Primary // this seemingly redundant datasource is apparently used behind
// ... the scenes and throws an 'unsatisfied dependency' if removed.
#Bean(name = "dataSource")
#ConfigurationProperties(prefix = "spring.datasource.primaryDB")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean
public DataSource dataSourcePrimary(){
HikariConfig config = new HikariConfig();
config.setDriverClassName(driver);
config.setJdbcUrl(url);
config.setUsername(username);
config.setPassword(password);
config.setAutoCommit(true);
return new HikariDataSource(config);
}
#Primary
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("dataSource") DataSource dataSource) {
return builder
.dataSource(dataSourcePrimary())
.packages("com.foo.bar.model")
.persistenceUnit("primaryDB")
.build();
}
#Primary
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("entityManagerFactory") EntityManagerFactory
entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
And "otherDB":
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "otherDBEntityManagerFactory",
transactionManagerRef = "otherDBTransactionManager",
basePackages = { "com.foo.bar.otherDB" }
)
public class OtherDBConfig {
#Value("${spring.datasource.otherDB.driverClassName}")
private String driver;
#Value("${spring.datasource.otherDB.url}")
private String url;
#Value("${spring.datasource.otherDB.username}")
private String username;
#Value("${spring.datasource.otherDB.password}")
private String password;
#Bean(name = "otherDBDataSource")
#ConfigurationProperties(prefix = "spring.datasource.otherDB")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean
public DataSource dataSourceOtherDB(){
HikariConfig config = new HikariConfig();
config.setDriverClassName(driver);
config.setJdbcUrl(url);
config.setUsername(username);
config.setPassword(password);
config.setAutoCommit(true);
return new HikariDataSource(config);
}
#Bean(name = "otherDBEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean otherDBEntityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("otherDBDataSource") DataSource dataSource) {
return
builder
.dataSource(dataSourceOtherDB())
.packages("com.foo.bar.otherDB.model")
.persistenceUnit("otherDB")
.build();
}
#Bean(name = "otherDBTransactionManager")
public PlatformTransactionManager otherDBTransactionManager(
#Qualifier("otherDBEntityManagerFactory") EntityManagerFactory
otherDBEntityManagerFactory) {
return new JpaTransactionManager(otherDBEntityManagerFactory);
}
}
The package structure looks like this:
Of course, having multiple data sources is an anti-pattern for modern microservices APIs; so this solution is fundamentally for monoliths (and distributed monoliths) :-)

Exception java.sql.SQLSyntaxErrorException: Schema 'SA' does not exist, when trying to make a query to Oracle DB

I've been with a mistake for a few weeks now, I wonder if anyone around here can shed some light...
I have a web application, I built it using Spring Boot and it connects to two databases, both Oracle.
In my development environment I deploy in the Spring Boot embedded tomcat and everything works fine. The problem occurs when I deploy in Weblogic (Integration environment) which, when trying to login, returns the following exception at trying to execute a select:
<Dec 27, 2019 1:58:16,335 PM CET> <Warning> <org.hibernate.engine.jdbc.spi.SqlExceptionHelper> <BEA-000000> <SQL Error: 30000, SQLState: 42Y07>
<Dec 27, 2019 1:58:16,336 PM CET> <Error> <org.hibernate.engine.jdbc.spi.SqlExceptionHelper> <BEA-000000> <Schema 'SA' does not exist>
<Dec 27, 2019 1:58:16,343 PM CET> <Error> <org.springframework.boot.web.servlet.support.ErrorPageFilter> <BEA-000000> <Forwarding to error page from request [/login_ldap] due to exception [could not prepare statement; SQL [select userentity0_.id as id1_6_, userentity0_.name as name2_6_, userentity0_.operator as operator3_6_, userentity0_.profile as profile4_6_, userentity0_.roles as roles5_6_, userentity0_.theme as theme6_6_, userentity0_.token as token7_6_ from USERS userentity0_ where userentity0_.name=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement]
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [select userentity0_.id as id1_6_, userentity0_.name as name2_6_, userentity0_.operator as operator3_6_, userentity0_.profile as profile4_6_, userentity0_.roles as roles5_6_, userentity0_.theme as theme6_6_, userentity0_.token as token7_6_ from USERS userentity0_ where userentity0_.name=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:240)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:223)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
....
....
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:415)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:355)
Caused By: org.hibernate.exception.SQLGrammarException: could not prepare statement
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:111)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:181)
....
....
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:415)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:355)
Caused By: java.sql.SQLSyntaxErrorException: Schema 'SA' does not exist
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
....
....
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:415)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:355)
Caused By: ERROR 42Y07: Schema 'SA' does not exist
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.catalog.DataDictionaryImpl.getSchemaDescriptor(Unknown Source)
at org.apache.derby.iapi.sql.StatementUtil.getSchemaDescriptor(Unknown Source)
....
....
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:415)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:355)
>
I have been visiting many forums and they all refer to an error that can occur when using Derby DB, and in fact, in the trace of the exception I can see org.apache.derby.iapi.error.StandardException (I can't understand why).
The problem has appeared when I added the second datasource, since the configuration that Spring Boot brought by default was not good for me and, therefore, I had to configure it "by hand".
Maybe, I have some erroneous configuration, but I can't find it.My application.properties is:
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:#//IP1:PUERTO1/SERVICIO1
spring.datasource.jdbc-url=jdbc:oracle:thin:#//IP1:PUERTO1/SERVICIO1
spring.datasource.username=USERNAME1
spring.datasource.password=PASSWORD1
spring.datasource.hikari.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.hikari.connection-init-sql=ALTER SESSION SET CURRENT_SCHEMA=USERNAME1
spring.remd-datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.remd-datasource.url=jdbc:oracle:thin:#//IP2:PUERTO2/SERVICIO2
spring.remd-datasource.jdbc-url=jdbc:oracle:thin:#//IP2:PUERTO2/SERVICIO2
spring.remd-datasource.username=USERNAME2
spring.remd-datasource.password=PASSWORD2
spring.remd-datasource.hikari.driver-class-name=oracle.jdbc.OracleDriver
spring.remd-datasource.hikari.connection-init-sql=ALTER SESSION SET CURRENT_SCHEMA=USERNAME2
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
logging.level.org.springframework.web=ERROR
logging.level.org.springframework.security.access.intercept=debug
logging.level.org.springframework.security=ERROR
logging.level.com.hpe=DEBUG
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.file=./logs/serverApplication.log
server.error.whitelabel.enabled=false
And the configuration classes that I created for the two datasources:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory",
basePackages = { "com.project.repository.clar" }
)
public class ClarDataSourceConfiguration {
#ConfigurationProperties(prefix = "spring.datasource")
#Primary
#Bean(name = "dataSource")
public DataSource dataSource(DataSourceProperties properties) {
return DataSourceBuilder.create(properties.getClassLoader())
.type(HikariDataSource.class)
.driverClassName(properties.determineDriverClassName())
.url(properties.determineUrl())
.username(properties.determineUsername())
.password(properties.determinePassword())
.build();
}
#Primary
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder, #Qualifier("dataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("com.project.model.clar").persistenceUnit("clar").build();
}
#Primary
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(#Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
and
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "remdEntityManagerFactory",
transactionManagerRef = "remdTransactionManager",
basePackages = { "com.project.repository.remd" }
)
public class RemdDataSourceConfiguration {
#ConfigurationProperties(prefix = "spring.remd-datasource")
#Bean(name = "remdDataSource")
public DataSource dataSource(DataSourceProperties properties) {
return DataSourceBuilder.create(properties.getClassLoader())
.type(HikariDataSource.class)
.driverClassName(properties.determineDriverClassName())
.url(properties.determineUrl())
.username(properties.determineUsername())
.password(properties.determinePassword())
.build();
}
#Bean(name = "remdEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean remdEntityManagerFactory(
EntityManagerFactoryBuilder builder, #Qualifier("remdDataSource") DataSource remdDataSource) {
return builder.dataSource(remdDataSource).packages("com.project.model.remd").persistenceUnit("remd").build();
}
#Bean(name = "remdTransactionManager")
public PlatformTransactionManager remdTransactionManager(#Qualifier("remdEntityManagerFactory") EntityManagerFactory remdEntityManagerFactory) {
return new JpaTransactionManager(remdEntityManagerFactory);
}
}
Thanks to everyone in advance and regards!!
I'm aware this may not answer your question, but I ran into the same issue (defining multiple datasources) a while back; this is my solution:
#Configuration
#EnableTransactionManagement
class PersistenceConfig {
#Bean(name = "oneDS")
#ConfigurationProperties(prefix = "custom-namespace.datasource.one")
public DataSource oneDataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "mainDS")
#ConfigurationProperties(prefix = "custom-namespace.datasource.main")
public DataSource mainDataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "twoDS")
#ConfigurationProperties(prefix = "custom-namespace.datasource.two")
public DataSource twoDataSource() {
return DataSourceBuilder.create().build();
}
#Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(mainDataSource());
}
// ...other beans using the other datasources
}
...and this is how the application.yml looks like for those settings:
Notice there is NO built-in configuration for the data-sources in application.yml.
custom-namespace:
datasource:
one:
driver-class-name: oracle.jdbc.OracleDriver
jdbc-url: jdbc:oracle:thin:/#oneDS
main:
driver-class-name: oracle.jdbc.OracleDriver
jdbc-url: jdbc:oracle:thin:/#mainDS
two:
driver-class-name: oracle.jdbc.OracleDriver
jdbc-url: jdbc:oracle:thin:/#twoDS
server:
compression:
enabled: true
port: "${SERVER_PORT:8080}"
ssl:
enabled: true
spring:
application:
name: "spring-core"
banner:
charset: UTF-8
http:
encoding:
charset: UTF-8
enabled: true
force: true
main:
banner-mode: "off"
output:
ansi:
enabled: detect
profiles:
active: default
---
spring:
profiles: development
---
spring:
profiles: production
---
server:
ssl:
enabled: false
spring:
main:
banner-mode: console
profiles: sandbox
---
spring:
profiles: test
Since I'm using Spring profiles they must be "activated"; e.g.: --spring.profiles.active=sandbox.
I've found the mistake.
For a reason that I can't understand, Spring is not charging the properties defined in application.properties file that I'm trying to read from my configuration class (properties.determineDriverClassName(), properties.determineUrl(), etc). Instead, if I hardcode the values all works perfectly.As a workaround I've defined these properties in another properties file and works fine, but I'll continue investigating why properties from my application.properties aren't being charging.

Spring Boot - Ehcache Second Level Cache Integration

I am trying to hold some variables in the second level cache. I have read and applied the instructions in Baeldung. However, it keeps giving this error:
Caused by: org.hibernate.cache.NoCacheRegionFactoryAvailableException: Second-level cache is used in the application, but property hibernate.cache.region.factory_class is not given; please either disable second level cache or set correct region factory using the hibernate.cache.region.factory_class setting and make sure the second level cache provider (hibernate-infinispan, e.g.) is available on the classpath.
at org.hibernate.cache.internal.NoCachingRegionFactory.buildTimestampsRegion(NoCachingRegionFactory.java:88)
at org.hibernate.cache.spi.UpdateTimestampsCache.(UpdateTimestampsCache.java:57)
at org.hibernate.internal.CacheImpl.(CacheImpl.java:53)
at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:28)
at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:20)
at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:49)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:254)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:228)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.getService(SessionFactoryServiceRegistryImpl.java:68)
at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:244)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
I added this dependency to pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.2.2.Final</version>
</dependency>
Then, added these lines to application.properties:
hibernate.cache.use_second_level_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.use_query_cache=true
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
At the top of the entity classes, I added these caching annotations:
#Cacheable
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
In the configuration file, I added #EnableCaching annotation.
Here are other beans and methods I added to configuration file:
#Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("spring.datasource.driver-class-name")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("spring.datasource.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("spring.datasource.username")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("spring.datasource.password")));
return dataSource;
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
return hibernateProperties;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
Is there something wrong with the configuration methods?
Note: This is a spring-boot project.

ERROR: Cannot create PoolableConnectionFactory (isValid() returned false)

What is the problem? I Use H2 DATABASE
Someone have a solution for my problem ?
I Use H2 DATA BASE, Hibernate 5
This hy HibernateConfig.java
package com.train.shoponlinebackend.config;
#Configuration
#ComponentScan(basePackages = {"com.train.shoponlinebackend.dto"})
#EnableTransactionManagement
public class HibernateConfig {
private static String DATABASE_URL = "jdbc:h2:tcp://localhost/~/onlineshopping";
private static String DATABASE_DRIVER = "org.h2.Driver";
private static String DATABASE_DIALECT = "org.hibernate.dialect.H2Dialect";
private static String DATABASE_USERNAME = "sa";
private static String DATABASE_PASSWORD = "";
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(DATABASE_DRIVER);
dataSource.setUrl(DATABASE_URL);
dataSource.setUsername(DATABASE_USERNAME);
dataSource.setPassword(DATABASE_PASSWORD);
return dataSource;
}
#Bean
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
builder.addProperties(getHibernateProperties());
builder.scanPackages("com.train.shoponlinebackend.dto");
return builder.buildSessionFactory();
}
private Properties getHibernateProperties() {
// TODO Auto-generated method stub
Properties properties = new Properties();
properties.put("hibernate.dialect", DATABASE_DIALECT);
properties.put("hibernate.show_sql", true);
properties.put("hibernate.format_sql", true);
return properties;
}
#Bean
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}
My method in DAO IMPL :
#Repository("categoryDAO")
public class CategoryDAOImpl implements CategoryDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public boolean add(Category category) {
try {
// add category
sessionFactory.getCurrentSession().persist(category);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
My JUNIT Test
#Test
public void testAdCategory(){
category = new Category();
category.setActive(true);
category.setDescription("This is some description of TV");
category.setImageURL("CAT_1.png");
category.setName("Television");
assertEquals("Success added category", true, categoryDAO.add(category));
}
My Error when running my junit test :
org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:542)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy28.add(Unknown Source)
at com.train.shoponlinebackend.test.CategoryTestCase.testAdCategory(CategoryTestCase.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:102)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:129)
at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:514)
at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:448)
... 32 more
Caused by: java.sql.SQLException: Cannot create PoolableConnectionFactory (isValid() returned false)
at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2294)
at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2039)
at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:99)
... 35 more
Caused by: java.sql.SQLException: isValid() returned false
at org.apache.commons.dbcp2.PoolableConnection.validate(PoolableConnection.java:284)
at org.apache.commons.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:357)
at org.apache.commons.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2307)
at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2290)
... 40 more
Check the version of h2 in your pom.xml file.
If the h2 database engine is 1.4.194, then the dependency you are adding through maven or gradle for h2 database driver should be also 1.4.194.
I am going to restate the root cause (and solution) since you will run into this issue every time you want to use H2. The cause is so simple and so obvious..
After you install H2 and get a working connect, go and check the precise version of the H2 bin Jar (the one with the main class) you installed (again — at the H2 server location not your program). Here is what I am using (this month..):
C:\Program Files (x86)\H2\bin\h2-1.4.195.jar
Of course your H2 server could be on another platform or location..
Rule: When you setup your class path (i.e. your maven POM file for the a project) **always specify the EXACT same H2 jar file in your program as the one used by your H2 server ** (i.e the one above for me). H2 is extremely finicky on this.
A maven user might have this specified in their POM file:
<!-- H2 DATABASE -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version> <!-- Does not match the server jar -->
</dependency>
See the "193"? That is different the server (see jar above) above (using 195).
Changing the pom to use 195 will fix the issue (substitute whatever version of H2 you are using here)
<!-- H2 DATABASE -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.195</version> <!-- Matches the server JAR -->
</dependency>
If you get frustrated or can't get to a maven repository, just copy the H2 installed server jar file (outside your project) above into your project (outside of maven) and move on..

Is there a way to integrate spring-batch-admin and spring-boot properly?

According to the documentation spring batch admin is very easy to embed into the existing application. Simply copying web.xml and index.jsp then adding needed dependencies is enough getting it to work.
But if I want to use it in an existing spring boot project it getting worse. According to this example the configuration is a bit hacky but it works. UNTIL I try to use #EnableBatchProcessing annotation in my configuriton bean. Then I get the following exception.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobBuilders' defined in class path resource [org/springframework/batch/core/configuration/annotation/SimpleBatchConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.batch.core.configuration.annotation.JobBuilderFactory org.springframework.batch.core.configuration.annotation.AbstractBatchConfiguration.jobBuilders() throws java.lang.Exception] threw exception; nested exception is java.lang.ClassCastException: org.springframework.batch.core.repository.support.JobRepositoryFactoryBean$$EnhancerBySpringCGLIB$$49fa0273 cannot be cast to org.springframework.batch.core.repository.JobRepository
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at demo.Application.main(Application.java:35)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.batch.core.configuration.annotation.JobBuilderFactory org.springframework.batch.core.configuration.annotation.AbstractBatchConfiguration.jobBuilders() throws java.lang.Exception] threw exception; nested exception is java.lang.ClassCastException: org.springframework.batch.core.repository.support.JobRepositoryFactoryBean$$EnhancerBySpringCGLIB$$49fa0273 cannot be cast to org.springframework.batch.core.repository.JobRepository
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 17 more
Caused by: java.lang.ClassCastException: org.springframework.batch.core.repository.support.JobRepositoryFactoryBean$$EnhancerBySpringCGLIB$$49fa0273 cannot be cast to org.springframework.batch.core.repository.JobRepository
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$$EnhancerBySpringCGLIB$$b5c6eb04.jobRepository(<generated>)
at org.springframework.batch.core.configuration.annotation.AbstractBatchConfiguration.jobBuilders(AbstractBatchConfiguration.java:58)
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$$EnhancerBySpringCGLIB$$b5c6eb04.CGLIB$jobBuilders$8(<generated>)
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$$EnhancerBySpringCGLIB$$b5c6eb04$$FastClassBySpringCGLIB$$d88bd05f.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$$EnhancerBySpringCGLIB$$b5c6eb04.jobBuilders(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 18 more
My configuration is quite simple I have two configuration beans
#Configuration
#ImportResource({"classpath:/org/springframework/batch/admin/web/resources/servlet-config.xml",
"classpath:/org/springframework/batch/admin/web/resources/webapp-config.xml"})
public class BatchAdminConfiguration {
}
and
#Configuration
#EnableBatchProcessing
public class BatchImporterConfiguration {
}
When I remove #EnableBatchProcessing and try to create jobs with JobBuilderFactory and use #StepScope annotation I'm getting other ClassCastExceptions.
Now I'm using xml based configuration to create jobs, steps and other beans. It work well but I would actually preffer xml free configuration. Is there a way to easily integrate spring boot, spring batch and spring batch admin ?
Spring Batch Admin 2.0-BUILD-SNAPSHOT introduce a new Annoation #EnableBatchAdmin for easy to integrate with spring boot.
There is also a samples project https://github.com/spring-projects/spring-batch-admin-samples.
The short answer is that you won't want to use #EnableBatchProcessing with Spring Batch Admin. SBA provides a number of beans on a global scale that the #EnableBatchProcessing also provides. SBA 2.0 (currently in development) will probably fill the gaps between what is currently there and what #EnableBatchProcessing provides (specifically providing the JobBuilderFactory and StepBuilderFactory).
To get yourself running, you should be able to (I haven't tired this myself) configure in the META-INF/spring/batch/override/ directory a JobBuilderFactory and a StepBuilderFactory for global use. From there, you can use XML files in the META-INF/spring/batch/jobs directory that do nothing more than component scan for your #Configuration classes. However, leave off the #EnableBatchProcessing because of the duplication of beans.
For the record, this isn't an Spring Boot issue since #EnableBatchProcessing is a Spring Batch annotation, not a Boot one.
to complete the answer, here is the code to create the two beans once you disable the #EnableBatchProcessing annotation
#Autowired
JobRepository jobRepository;
#Autowired
PlatformTransactionManager transactionManager;
#Bean
public JobBuilderFactory jobBuilderFactory() {
return new JobBuilderFactory(jobRepository);
}
#Bean
public StepBuilderFactory stepBuilderFactory() {
return new StepBuilderFactory(jobRepository, transactionManager);
}
I've a working version here based on the same example (I forked the original one): https://github.com/vesperaba/spring-batch-admin-spring-boot.
I followed Michael Minella advice and I overwrote the SpringBatch property holder with a custom one.
I also added a job to check it's working now
This ClassCastException is caused by
classpath:/org/springframework/batch/admin/web/resources/servlet-config.xml
loading
META-INF/spring/batch/servlet/resources/resource-context.xml
which contains
<mvc:annotation-driven />
This conflicts with the mvc configuration in the Spring Java configuration class. The following class can be used to embed Spring Batch Admin within an existing application that uses Java configuration.
#Configuration
#EnableWebMvc
#ImportResource({"classpath*:/META-INF/spring/batch/bootstrap/**/*.xml"
, "classpath*:/META-INF/spring/batch/override/**/*.xml"
, "classpath*:/org/springframework/batch/admin/web/resources/webapp-config.xml"
, "classpath*:/META-INF/spring/batch/servlet/manager/**/*.xml"
, "classpath:base-menu-config.xml"
})
public class SpringBatchAdminConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/META-INF/");
}
#Bean
public SimpleControllerHandlerAdapter simpleControllerHandlerAdapter() {
return new SimpleControllerHandlerAdapter();
}
#Bean
public BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() {
return new BeanNameUrlHandlerMapping();
}
#Bean
public BeanNameViewResolver beanNameViewResolver() {
return new BeanNameViewResolver();
}
#Bean(name = "defaultResources")
public PropertiesFactoryBean defaultResources() {
return new PropertiesFactoryBean();
}
#Bean(name = "jsonResources")
public PropertiesFactoryBean jsonResources() {
return new PropertiesFactoryBean();
}
#Bean
public HomeController homeController() throws IOException {
HomeController homeController = new HomeController();
homeController.setDefaultResources(defaultResources().getObject());
homeController.setJsonResources(jsonResources().getObject());
return homeController;
}
#Bean
public MenuManager menuManager() {
return new MenuManager();
}
#Bean(name = "freemarkerConfig")
public HippyFreeMarkerConfigurer hippyFreeMarkerConfigurer() {
HippyFreeMarkerConfigurer hippyFreeMarkerConfigurer = new HippyFreeMarkerConfigurer();
hippyFreeMarkerConfigurer.setTemplateLoaderPaths("/WEB-INF/web", "classpath:/org/springframework/batch/admin/web");
hippyFreeMarkerConfigurer.setPreferFileSystemAccess(false);
hippyFreeMarkerConfigurer.setFreemarkerVariables(Collections.singletonMap("menuManager", (Object) menuManager()));
Properties freemarkerSettings = new Properties();
freemarkerSettings.put("default_encoding", "UTF-8");
freemarkerSettings.put("output_encoding", "UTF-8");
hippyFreeMarkerConfigurer.setFreemarkerSettings(freemarkerSettings);
return hippyFreeMarkerConfigurer;
}
public AjaxFreeMarkerView parentLayout() {
AjaxFreeMarkerView ajaxFreeMarkerView = new AjaxFreeMarkerView();
FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
freeMarkerViewResolver.setExposeSpringMacroHelpers(false);
freeMarkerViewResolver.setAllowRequestOverride(true);
ajaxFreeMarkerView.setViewResolver(freeMarkerViewResolver);
Properties attributes = new Properties();
attributes.put("titleCode", "home.title");
attributes.put("titleText", "Spring Batch Admin");
ajaxFreeMarkerView.setAttributes(attributes);
return ajaxFreeMarkerView;
}
#Value("#{resourceService.servletPath}")
private String servletPath;
#Bean(name="standard")
public AjaxFreeMarkerView standard() {
AjaxFreeMarkerView standard = parentLayout();
standard.setUrl("/layouts/html/standard.ftl");
standard.setContentType("text/html;charset=UTF-8");
standard.getAttributesMap().put("body", "/layouts/html/home.ftl");
standard.getAttributesMap().put("servletPath", servletPath);
return standard;
}
#Bean(name="standard.rss")
public AjaxFreeMarkerView standardRss() {
AjaxFreeMarkerView standardRss = parentLayout();
standardRss.setUrl("/layouts/html/standard.ftl");
standardRss.setContentType("text/xml");
standardRss.getAttributesMap().put("body", "/layouts/rss/home.ftl");
standardRss.getAttributesMap().put("servletPath", servletPath);
return standardRss;
}
#Bean(name="standard.json")
public AjaxFreeMarkerView standardJson() {
AjaxFreeMarkerView standardJson = parentLayout();
standardJson.setUrl("/layouts/json/standard.ftl");
standardJson.setContentType("application/json");
standardJson.getAttributesMap().put("body", "/layouts/json/home.ftl");
standardJson.getAttributesMap().put("servletPath", servletPath);
return standardJson;
}
#Bean(name="home")
public AjaxFreeMarkerView home() {
return standard();
}
#Bean(name="home.json")
public AjaxFreeMarkerView homeJson() {
AjaxFreeMarkerView homeJson = standardJson();
homeJson.getAttributesMap().put("body", "/layouts/json/home.ftl");
return homeJson;
}
}
A single XML file is also required for the abstract base menu which is referenced elsewhere in the Spring Batch Admin project. This is required as abstract beans can not be provided from a Spring Java configuration.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="baseMenu" abstract="true">
<property name="prefix" value="#{resourceService.servletPath}" />
</bean>
</beans>
Maven dependencies. Take care to ensure only a single version of the base Spring framework is pulled in by Maven.
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-admin-manager</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
<version>1.8.0.10</version>
</dependency>
Spring batch also expects in a default configuration for the following files to exist at the root of the classpath.
batch-default.properties
# Default placeholders for database platform independent features
batch.remote.base.url=http://localhost:8080/spring-batch-admin-sample
# Non-platform dependent settings that you might like to change
batch.job.configuration.file.dir=/tmp/config
build.artifactId=1
build.version=1
build.buildNumber=1
build.timestamp=1
log.enableConsole=true
batch-hsql.properties
# Placeholders batch.*
# for HSQLDB:
batch.jdbc.driver=org.hsqldb.jdbcDriver
batch.jdbc.url=jdbc:hsqldb:mem:testdb;sql.enforce_strict_size=true
# Override and use this one in for a separate server process so you can inspect
# the results (or add it to system properties with -D to override at run time).
# batch.jdbc.url=jdbc:hsqldb:hsql://localhost:9005/samples
batch.jdbc.user=sa
batch.jdbc.password=
batch.database.incrementer.class=org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer
batch.schema.script=classpath*:/org/springframework/batch/core/schema-hsqldb.sql
batch.drop.script=classpath*:/org/springframework/batch/core/schema-drop-hsqldb.sql
batch.business.schema.script=classpath:/business-schema-hsqldb.sql
# Non-platform dependent settings that you might like to change
# batch.data.source.init=true
business-schedule-hsqldb.sql
DROP TABLE ERROR_LOG IF EXISTS;
CREATE TABLE ERROR_LOG (
JOB_NAME CHAR(20) ,
STEP_NAME CHAR(20) ,
MESSAGE VARCHAR(300) NOT NULL
) ;

Categories

Resources