DataSourceInitializer does not get called - java

I am setting up java config for database in my spring mvc app, and what I cannot figure out is why DataSourceInitializer bean does not get created, i.e. dataSourceInitializer method is never called.
#Configuration
#EnableJpaRepositories(basePackageClasses = {CustomerRepository.class})
#EnableTransactionManagement
public class DatabaseConfig {
#Resource
Environment environment;
#Bean
public NamedParameterJdbcTemplate jdbcTemplate(DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.user"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.pwd"));
return dataSource;
}
#Bean
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
final DataSourceInitializer initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource);
initializer.setDatabasePopulator(databasePopulator());
return initializer;
}
#Bean
public DatabasePopulator databasePopulator() {
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScript(new ClassPathResource("classpath:/db/sql/create-db.sql", DatabaseConfig.class));
databasePopulator.addScript(new ClassPathResource("classpath:/db/sql/insert-data.sql", DatabaseConfig.class));
return databasePopulator;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) throws Exception {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setPersistenceUnitName("CustomersPU");
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.myapp.domain");
factory.setDataSource(dataSource);
factory.setJpaProperties(jpaProperties());
return factory;
}
Properties jpaProperties() {
Properties props = new Properties();
props.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
props.put("hibernate.hbm2ddl.auto", "validate");
...
return props;
}
}
UPDATE: Exception that I get is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/myapp/conf/DatabaseConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: CustomersPU] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at ....
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: CustomersPU] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:877)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:805)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at ...
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [CUSTOMERS]
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:67)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:50)
at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:91)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:484)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:802)
... 62 more
What I am looking for is to have it configured similar to this configuration: embedded database + special username and password + paths to schema and insertion sql files. Like described here https://github.com/JohnathanMarkSmith/HelloSpringJavaBasedJavaConfig
UPDATE
If I just use EmbeddableDatabase, then it does not allow me to define username, password and DB connection URL, which is necessary to me. The following example works, but it does not allow me to define username, password and DB connection URL.
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:/db/sql/create-db.sql")
.addScript("classpath:/db/sql/insert-data.sql")
.build();
}

Related

Spring boot Hibernate data source exception null exception on application start up

Getting
ERROR [SpringApplication] Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myEntityManagerFactory' defined in class path resource [com/employees/service/config/DBConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean
Caused by: java.lang.NullPointerException at
org.hibernate.boot.model.source.internal.hbm.ModelBinder$AbstractPluralAttributeSecondPass.bindCollectionElement(ModelBinder.java:3554)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at
org.hibernate.boot.model.source.internal.hbm.ModelBinder$AbstractPluralAttributeSecondPass.doSecondPass(ModelBinder.java:3133)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at
org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1696)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at
org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1664)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:287)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at
org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
for code
#ConfigurationProperties(prefix = "spring.datasource.employees")
#Bean
public DataSource myDataSource() {
return DataSourceBuilder.create().build();
}
#Bean
public LocalContainerEntityManagerFactoryBean myEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean employees = createEntityManagerFactory(
myDataSource(), "Employees",
MyMapping.MAPPINGS);
return employees;
}
#Bean
public EntityManager myEntityManager(#Qualifier("myEntityManagerFactory")
EntityManagerFactory emf) {
return entityManager(emf);
}
#Bean
public JpaTransactionManager myTransactionManager(#Qualifier("myEntityManagerFactory")
EntityManagerFactory emf) {
return transactionManager(emf);
}
#Bean
public TransactionHelper myTransactionHelper(
#Qualifier("myTransactionManager")
JpaTransactionManager transactionManager) {
TransactionHelper transactionHelper = new TransactionHelper();
transactionHelper.setPlatformTransactionManager(transactionManager);
return transactionHelper;
}
// Common methods
private LocalContainerEntityManagerFactoryBean createEntityManagerFactory(
DataSource dataSource, String persistenceUnitName, String[] mappings) {
MyLocalContainerEntityManagerFactoryBean entityManagerFactory
= new MyLocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource);
entityManagerFactory.setPersistenceUnitName(persistenceUnitName);
entityManagerFactory.setPackagesToScan("com.employees.domain");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
entityManagerFactory.setJpaProperties(additionalProperties());
if (mappings != null) {
entityManagerFactory.setMappingResources(mappings);
}
return entityManagerFactory;
}
private JpaTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
private EntityManager entityManager(EntityManagerFactory emf) {
return SharedEntityManagerCreator.createSharedEntityManager(emf);
}
#Bean
#Primary
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "none");
// properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.implicit_naming_strategy",
"com.employees.domain.hibernate.BackwardsCompatibleImplicitNamingStrategy");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
return properties;
}
#Bean public TraceProperties traceProperties() {
TraceProperties traceProperties = new TraceProperties();
Set<TraceProperties.Include> includes = new HashSet<>();
includes.addAll(Arrays.asList(TraceProperties.Include.values()));
traceProperties.setInclude(includes);
return traceProperties;
}
In my case, this issue was related to hibernate mappings. There was one .hbm file that had a nested table in it or an association that was not defined when creating database connection entity manager factory.

Connection with multiple database with spring boot

Showing error while connecting to database using spring boot:
classMethod FAILED
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/tomtom/workflow/iris/uitest/DatabaseConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
Caused by:
javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
Caused by:
org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
Caused by:
org.postgresql.util.PSQLException: The connection attempt failed.
Caused by:
java.net.SocketTimeoutException: connect timed out
Properties:
# PostgreSQL DB - "iris"
spring.datasource.jdbc-url= jdbc:postgresql://172.xx.xx.93:5442/workflow?currentSchema=workflow
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.username=workflow
spring.datasource.password=workflow
# PostgreSQL DB - "accesspoint"
secondary.datasource.jdbc-url=jdbc:postgresql://172.xx.xxx.44:5442/workflow?currentSchema=accesspoint
secondary.datasource.username=dba_admin
secondary.datasource.password=dba_admin
hibernate.dialect=org.hibernate.dialect.PostgreSQL82Dialect
hibernate.hbm2ddl.auto= update
Classes For bean.For secondary datasource:
package com.tomtom.workflow.acesspoint;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "accessPointEntityManagerFactory",
transactionManagerRef = "accessPointTransactionManager",
basePackages = { "com.tomtom.workflow.acesspoint" }
)
public class AccessPointDbConfiguration {
#Autowired
private Environment env;
#Bean(name = "accessPointDataSource")
#ConfigurationProperties(prefix = "accesspoint.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "accessPointEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean accessPointEntityManagerFactory() {
/*
* return builder .dataSource(dataSource)
* .packages("com.tomtom.workflow.acesspoint") .persistenceUnit("baseline_info")
* .build();
*/
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.tomtom.workflow.acesspoint" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
#Bean(name = "accessPointTransactionManager")
public PlatformTransactionManager accessPointTransactionManager(
#Qualifier("accessPointEntityManagerFactory") EntityManagerFactory accessPointEntityManagerFactory) {
return new JpaTransactionManager(accessPointEntityManagerFactory);
}
}
For Primary datasource i have written this class.
package com.tomtom.workflow.iris.uitest;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", basePackages = {
"com.tomtom.workflow.iris.uitest" })
#Profile(Profiles.DATABASE)
class DatabaseConfiguration {
#Autowired
private Environment env;
#Primary
#Bean(name = "dataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.tomtom.workflow.iris.uitest.db.model" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
#Primary
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
I have connected both the database by pg admin and they are active.
Please help.

Hibernate error when hbm2ddl.auto is update

#Configuration
#EnableTransactionManagement
#ComponentScans(value = {
#ComponentScan("org.kalifornia.fridgeapp.DAO"),
#ComponentScan("org.kalifornia.fridgeapp.service")
} )
#PropertySource("classpath:mysql.properties")
public class HibernateConfig {
#Autowired
private ApplicationContext context;
#Autowired
private Environment env;
#Bean
public LocalSessionFactoryBean getSessionFactory()
{
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
try
{
factoryBean.setHibernateProperties(hibernateProperties());
factoryBean.afterPropertiesSet();
factoryBean.setDataSource(restDataSource());
factoryBean.setAnnotatedClasses(FridgeUser.class);
factoryBean.setAnnotatedClasses(Community.class);
factoryBean.setAnnotatedClasses(Container.class);
factoryBean.setAnnotatedClasses(Item.class);
factoryBean.setAnnotatedClasses(Product.class);
} catch(IOException exception) {
System.out.print(exception.fillInStackTrace());
return null;
}
return factoryBean;
}
#Bean
public DataSource restDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/fridge");
dataSource.setUsername("root");
dataSource.setPassword("kaszanka");
return dataSource;
}
#Bean
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory().getObject());
return transactionManager;
}
Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
setProperty("show_sql", "true");
setProperty("hibernate.hbm2ddl.auto", "update");
}
};
}
}
I wrote that code from tutorial and it works now but when I try to change a hbm2ddl.auto from create to update I get this error:
$Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'DAOImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in org.kalifornia.fridgeapp.spring.config.HibernateConfig: Invocation of init method failed; nested exception is java.lang.UnsupportedOperationException: Not supported by BasicDataSource
According to your log nested exception is java.lang.UnsupportedOperationException: Not supported by BasicDataSource seems like an issue with BasicDataSource, try changing it to DriverManagerDataSource because it may be the case that BasicDataSource doesn't support hibernate.hbm2ddl.auto = update

Spring 4 + Spring repositories + hibernate 5: Error create java config

I have spring 4 app and I want use spring repositories. I tried include spring jpa_hibernate
compile 'org.springframework.data:spring-data-jpa:1.11.4.RELEASE'
compile group: 'org.hibernate', name: 'hibernate-core', version: '5.0.5.Final'
and create config like oficial spring doc:
#Configuration
#ComponentScan("my.domain")
#EnableJpaRepositories("my.domain")
#EnableTransactionManagement
public class ApplicationConfiguration {
#Bean
public Config getConfig() {
return ConfigLoader.load();
}
#Bean
#Autowired
public DataSource getDatasource(Config config) throws Exception {
Properties props = new Properties();
Config dbConfig = config.getConfig("db.config");
dbConfig.entrySet().forEach(entry -> props.put(entry.getKey(), entry.getValue().unwrapped()));
return new DataSourceFactory().createDataSource(props);
}
#Bean
#Autowired
public NamedParameterJdbcTemplate getJdbcTemplate(DataSource datasource) {
return new NamedParameterJdbcTemplate(datasource);
}
#Bean
#Autowired
public PlatformTransactionManager getTransactionManager(DataSource datasource) {
return new DataSourceTransactionManager(datasource);
}
#Bean
#Autowired
public EntityManagerFactory entityManagerFactory(DataSource datasource) {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setDataSource(datasource);
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
#Autowired
public PlatformTransactionManager transactionManager(DataSource datasource) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory(datasource));
return txManager;
}
}
But I get error when tried run app:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in my.ApplicationConfiguration:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate
[javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.IllegalStateException:
Failed to determine Hibernate PersistenceProvider
I used repositories in springboot and Configure in file, But I not found worck actual example for java config spring(not boot only simple core app)
As you are using latest Spring Data release, upgrade to the latest Hibernate release:
compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.10.Final'
Spring requires hibernate's EntityManagerFactory implementation which previosly was provisioned by separate jar which is now deprecated, so you need only single hibernate-core dependency.
Also consider using following configuration:
#Configuration
#ComponentScan("my.domain")
#EnableJpaRepositories("my.domain")
#EnableTransactionManagement
public class ApplicationConfiguration {
#Bean
public Config getConfig() {
return ConfigLoader.load();
}
#Bean
public DataSource getDatasource(Config config) throws Exception {
Properties props = new Properties();
Config dbConfig = config.getConfig("db.config");
dbConfig.entrySet().forEach(entry -> props.put(entry.getKey(), entry.getValue().unwrapped()));
return new DataSourceFactory().createDataSource(props);
}
#Bean
public NamedParameterJdbcTemplate getJdbcTemplate(DataSource datasource) {
return new NamedParameterJdbcTemplate(datasource);
}
#Bean
#Autowired
public PlatformTransactionManager getTransactionManager(DataSource datasource) {
return new DataSourceTransactionManager(datasource);
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setDataSource(dataSource());
factory.setPackagesToScan("my.domain");
return factory;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
}
You were referencsing old spring data documentation, current version is available here.

Meta tables for H2 db in Spring Batch

I am facing some trouble in order to configuring spring batch with h2 db
My configuration looks like this
#Configuration
#EnableBatchProcessing
public class BatchConfiguration implements BatchConfigurer {
#Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Driver.class.getName());
String h2Url = MessageFormat.format("jdbc:h2:file:{0}note;MODE=Oracle", System.getProperty("java.io.tmpdir"));
LOGGER.info("Using H2 with URL : {}", h2Url);
dataSource.setUrl(h2Url);
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
#Bean
public DefaultPersistenceUnitManager persistenceUnitManager() {
DefaultPersistenceUnitManager defaultPersistenceUnitManager = new DefaultPersistenceUnitManager();
defaultPersistenceUnitManager.setPersistenceXmlLocation("classpath*:/META-INF/persistence.xml");
defaultPersistenceUnitManager.setDefaultDataSource(dataSource());
return defaultPersistenceUnitManager;
}
#Bean
public HibernateJpaVendorAdapter jpaAdapter() {
HibernateJpaVendorAdapter jpaAdapter = new HibernateJpaVendorAdapter();
jpaAdapter.setDatabasePlatform(H2Dialect.class.getName());
jpaAdapter.setGenerateDdl(true);
jpaAdapter.setShowSql(true);
return jpaAdapter;
}
#Bean
public LocalContainerEntityManagerFactoryBean myEmf() {
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
localContainerEntityManagerFactoryBean.setDataSource(dataSource());
localContainerEntityManagerFactoryBean.setPersistenceUnitManager(persistenceUnitManager());
localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaAdapter());
localContainerEntityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
return localContainerEntityManagerFactoryBean;
}
public JobRepository getJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource());
factory.setTablePrefix("BATCH_");
factory.setTransactionManager(getTransactionManager());
factory.afterPropertiesSet();
return (JobRepository) factory.getObject();
}
public JobLauncher getJobLauncher() throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(getJobRepository());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
public JobExplorer getJobExplorer() throws Exception {
JobExplorerFactoryBean factory = new JobExplorerFactoryBean();
factory.setDataSource(dataSource());
factory.setTablePrefix("BATCH_");
factory.afterPropertiesSet();
return factory.getObject();
}
public PlatformTransactionManager getTransactionManager() {
return new JpaTransactionManager(myEmf().getObject());
}
}
When i start my job , it cannot connect to the db because the configuration is unable to retrieve the metadata ( while checking into the spring batch core. jar, i can find the h2 db schemas ) so i get the exception :
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT JOB_INSTANCE_ID, JOB_NAME from BATCH_JOB_INSTANCE where JOB_NAME = ? and JOB_KEY = ?]; nested exception is org.h2.jdbc.JdbcSQLException: Table "BATCH_JOB_INSTANCE" not found;
Any help would be appreciated
Thank you very much
A couple things:
That Exception isn't from not being able to connect to the database, but because the tables haven't been created (that Exception indicates that you can connect to the database). I don't see you running the initialization scripts.
You're overdoing all the wiring. Based on what you're doing, you shouldn't need to implement BatchConfigurer. All you need to provide is the DataSource bean. The rest should be provided for you...

Categories