I am having an application with mutiple datasource using Spring Boot and Spring data JPA.
I am getting the below exception hibernate.cache.region.factory_class not set, though I am setting it in code. Spring Boot is checking for it before I set, or not able to read my setting.
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.buildEntityRegion(NoCachingRegionFactory.java:83)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:364)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:845)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:844)
at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:338)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
... 130 more
8-Nov-2015 00:23:46.220 SEVERE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive D:\sw\apache-tomcat-8.0.23\webapps\SecurityValidator.war
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/SecurityValidator]]
I am having the below code. Only relevant parts are pasted:-
Spring Boot configuation class to show the excluding auto configurations:-
#EnableAsync
#SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,})
#ComponentScan("com.demo")
public class Initializer extends SpringBootServletInitializer {
My two datasource configuations:-
#Bean
public LocalContainerEntityManagerFactoryBean certEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(certificateDataSource());
em.setPackagesToScan(new String[] { "dao.entity.cert" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties1 = new HashMap<String, Object>();
properties1.put("hibernate.hbm2ddl.auto", "validate");
properties1.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
em.setJpaPropertyMap(properties1);
Properties properties = new Properties();
properties.setProperty("spring.jpa.properties.hibernate.cache.use_second_level_cache", "true");
properties.setProperty("spring.jpa.properties.hibernate.cache.use_query_cache", "true");
properties.setProperty("spring.jpa.properties.hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
properties.setProperty("spring.jpa.properties.hibernate.cache.default_cache_concurrency_strategy", "NONSTRICT_READ_WRITE");
properties.setProperty("spring.jpa.properties.hibernate.cache.region_prefix", "valCache");
properties.setProperty("spring.jpa.properties.hibernate.cache.use_structured_entries", "false");
properties.setProperty("spring.jpa.properties.h4m.adapter.class", "kr.pe.kwonnam.hibernate4memcached.spymemcached.SpyMemcachedAdapter");
properties.setProperty("spring.jpa.properties.h4m.timestamper.class", "kr.pe.kwonnam.hibernate4memcached.timestamper.HibernateCacheTimestamperMemcachedImpl");
properties.setProperty("spring.jpa.properties.h4m.adapter.spymemcached.hosts", "localhost:11211");
properties.setProperty("spring.jpa.properties.h4m.adapter.spymemcached.hashalgorithm", "KETAMA_HASH");
properties.setProperty("spring.jpa.properties.h4m.adapter.spymemcached.operation.timeout.millis", "5000");
properties.setProperty("spring.jpa.properties.h4m.adapter.spymemcached.transcoder", "kr.pe.kwonnam.hibernate4memcached.spymemcached.KryoTranscoder");
properties.setProperty("spring.jpa.properties.h4m.adapter.spymemcached.cachekey.prefix", "vali");
properties.setProperty("spring.jpa.properties.h4m.adapter.spymemcached.kryotranscoder.compression.threashold.bytes", "20000");
properties.setProperty("spring.jpa.properties.h4m.expiry.seconds", "600");
properties.setProperty("spring.jpa.properties.h4m.expiry.seconds.valCache.org.hibernate.cache.spi.UpdateTimestampsCache", "86400");
properties.setProperty("spring.jpa.properties.h4m.expiry.seconds.valCache.org.hibernate.cache.internal.StandardQueryCache", "3600");
properties.setProperty("spring.jpa.properties.h4m.expiry.seconds.valCache.cert", "1800");
properties.setProperty("spring.jpa.properties.h4m.expiry.seconds.valCache.users", "1800");
em.setJpaProperties(properties);
return em;
}
Similarly for the second data source also:-
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean userEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
..................
-----------------
}
I am using the below dependencies:-
</dependency>
<dependency>
<groupId>kr.pe.kwonnam.hibernate4memcached</groupId>
<artifactId>hibernate4-memcached-core</artifactId>
<version>0.7</version>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>kr.pe.kwonnam.hibernate4memcached</groupId>
<artifactId>hibernate4-memcached-spymemcached-adapter</artifactId>
<version>0.7</version>
</dependency>
Any suggestions or pointers is also welcomed.
UPDATE ERROR
I am still not able to move fully forward, but I am getting the below error now.
Caused by: net.spy.memcached.OperationTimeoutException: Mutate operation timed out,unable to modify counter [validator.validatorCache.users#]
at net.spy.memcached.MemcachedClient.mutate(MemcachedClient.java:1663) ~[spymemcached-2.10.2.jar:2.10.2]
at net.spy.memcached.MemcachedClient.mutateWithDefault(MemcachedClient.java:1835) ~[spymemcached-2.10.2.jar:2.10.2]
at net.spy.memcached.MemcachedClient.incr(MemcachedClient.java:1767) ~[spymemcached-2.10.2.jar:2.10.2]
at kr.pe.kwonnam.hibernate4memcached.spymemcached.SpyMemcachedAdapter.getNamespacedKey(SpyMemcachedAdapter.java:141) ~[hibernate4-memcached-spymemcached-adapter-0.7.jar:na]
at kr.pe.kwonnam.hibernate4memcached.spymemcached.SpyMemcachedAdapter.set(SpyMemcachedAdapter.java:167) ~[hibernate4-memcached-spymemcached-adapter-0.7.jar:na]
at kr.pe.kwonnam.hibernate4memcached.regions.GeneralDataMemcachedRegion.put(GeneralDataMemcachedRegion.java:86) ~[hibernate4-memcached-core-0.7.jar:na]
at kr.pe.kwonnam.hibernate4memcached.strategies.MemcachedRegionAccessStrategy.putFromLoad(MemcachedRegionAccessStrategy.java:52) ~[hibernate4-memcached-core-0.7.jar:na]
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:221) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:144) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1115) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.loader.Loader.processResultSet(Loader.java:973) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:921) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2554) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2540) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.loader.Loader.list(Loader.java:2365) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:497) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:236) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103) ~[hibernate-core-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:573) ~[hibernate-entitymanager-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:449) ~[hibernate-entitymanager-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:67) ~[hibernate-entitymanager-4.3.8.Final.jar:4.3.8.Final]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:315) ~[spring-data-jpa-1.8.0.RELEASE.jar:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:67) ~[spring-data-jpa-1.8.0.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_20]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_20]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_20]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_20]
I corrected the properties setting, by removing the properties bit. It was a typo. But now I am getting the above error.
The error net.spy.memcached.OperationTimeoutException: Mutate operation timed out appears to completely refer to memcached client/server interaction. Most likely the memcached server is not available on localhost:11211.
Can you try the below factory class:
net.sf.ehcache.hibernate.EhCacheRegionFactory
or
org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
Also, to debug - I would probably go ahead and check the actual jars and look for the presence of the factory class in that jar.
Related
after upgrading to Spring Batch 3.0.2 faced the following issue: chunk step fails trying to persist reader object which is not JPA Entity and not Serializable.
#Autowired
protected PlatformTransactionManager transactionManager;
#Autowired
protected JobRepository jobRepository;
[...]
#Bean
#JobScope
public Step processFileStep() {
return new StepBuilder("process-file", jobRepository)
.<Row, Matching>chunk(chunkSize, transactionManager)
.reader(reader())
.processor()
.writer(writer())
.build();
}
Row type here is org.apache.poi.ss.usermodel.Row which is passed by custom Apache POI Excel item reader. transactionManager and jobRepository are autoconfigured by Spring Data JPA.
On this step the following exception occurs:
java.lang.IllegalArgumentException: Not an entity [class org.apache.poi.xssf.usermodel.XSSFRow]
at org.hibernate.internal.SessionImpl.contains(SessionImpl.java:1604)
at org.springframework.batch.item.database.JpaItemWriter.doWrite(JpaItemWriter.java:112)
at org.springframework.batch.item.database.JpaItemWriter.write(JpaItemWriter.java:93)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:196)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:752)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:137)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:124)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:752)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:703)
at org.springframework.batch.item.database.JpaItemWriter$$SpringCGLIB$$0.write(<generated>)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.writeItems(SimpleChunkProcessor.java:203)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.doWrite(SimpleChunkProcessor.java:170)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.write(SimpleChunkProcessor.java:297)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.process(SimpleChunkProcessor.java:227)
at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:75)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:389)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:313)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:256)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:82)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:362)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:206)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:139)
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:241)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:227)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:196)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:137)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:124)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:218)
at jdk.proxy2/jdk.proxy2.$Proxy73.execute(Unknown Source)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:153)
at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:417)
at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:132)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:316)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:157)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:148)
at org.springframework.batch.core.launch.support.TaskExecutorJobLauncher.run(TaskExecutorJobLauncher.java:70)
at org.springframework.batch.integration.launch.JobLaunchingMessageHandler.launch(JobLaunchingMessageHandler.java:53)
at org.springframework.batch.integration.launch.JobLaunchingGateway.handleRequestMessage(JobLaunchingGateway.java:71)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:136)
at org.springframework.integration.handler.AbstractMessageHandler.doHandleMessage(AbstractMessageHandler.java:105)
at org.springframework.integration.handler.AbstractMessageHandler.handleWithMetrics(AbstractMessageHandler.java:90)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:70)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:115)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:133)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:106)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:72)
at org.springframework.integration.channel.AbstractMessageChannel.sendInternal(AbstractMessageChannel.java:373)
at org.springframework.integration.channel.AbstractMessageChannel.sendWithMetrics(AbstractMessageChannel.java:344)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:324)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:297)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:187)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:166)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:47)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:109)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:484)
at org.springframework.integration.handler.AbstractMessageProducingHandler.doProduceOutput(AbstractMessageProducingHandler.java:339)
at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:268)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:232)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:142)
at org.springframework.integration.handler.AbstractMessageHandler.doHandleMessage(AbstractMessageHandler.java:105)
at org.springframework.integration.handler.AbstractMessageHandler.handleWithMetrics(AbstractMessageHandler.java:90)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:70)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:115)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:133)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:106)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:72)
at org.springframework.integration.channel.AbstractMessageChannel.sendInternal(AbstractMessageChannel.java:373)
at org.springframework.integration.channel.AbstractMessageChannel.sendWithMetrics(AbstractMessageChannel.java:344)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:324)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:297)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:187)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:166)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:47)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:109)
at org.springframework.integration.endpoint.SourcePollingChannelAdapter.handleMessage(SourcePollingChannelAdapter.java:196)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.messageReceived(AbstractPollingEndpoint.java:474)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:460)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.pollForMessage(AbstractPollingEndpoint.java:412)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.lambda$createPoller$4(AbstractPollingEndpoint.java:348)
at org.springframework.integration.util.ErrorHandlingTaskExecutor.lambda$execute$0(ErrorHandlingTaskExecutor.java:57)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:55)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.lambda$createPoller$5(AbstractPollingEndpoint.java:341)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:96)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: org.hibernate.UnknownEntityTypeException: Unable to locate persister: org.apache.poi.xssf.usermodel.XSSFRow
at org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl.getEntityDescriptor(MappingMetamodelImpl.java:416)
at org.hibernate.internal.SessionImpl.contains(SessionImpl.java:1601)
... 106 common frames omitted
Batch configuration:
#Configuration
#EnableBatchProcessing(tablePrefix = "batch.batch_")
public class BatchConfiguration {
}
JPA configuration:
#Configuration
#EnableJpaRepositories("XXX.common.repository")
#EntityScan("XXX.common.model")
public class JpaConfig {
}
JPA dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>3.0.2</version>
</dependency>
Before this updage from Spring Batch 2.6.6 to Spring Batch 3.0.2 chunk() method did not have transactionManager parameter and this code worked as intended.
It seems like Map-based job repository should work in this case but it's not a production-ready solution.
Is there any way to use org.apache.poi.ss.usermodel.Row (or any other non-JPA object) as reader output with newer Spring Batch version with persistent storage?
Thanks in advance.
By debugging Spring Batch source code found that JpaItemWriter tries to persist list of Row's instead of Matching ones.
Found a silly mistake in my code:
#Bean
#JobScope
public Step processFileStep() {
return new StepBuilder("process-file", jobRepository)
.<Row, Matching>chunk(chunkSize, transactionManager)
.reader(reader())
.processor()
.writer(writer())
.build();
}
this part is missing an actual processor.
So my POI list of Row's passed directly to JPA writer. I've made my processor dummy for testing purposes and never checked that it was actually called.
Correct Step code is
#Bean
#JobScope
public Step processFileStep() {
return new StepBuilder("process-file", jobRepository)
.<Row, Matching>chunk(chunkSize, transactionManager)
.reader(reader())
.processor(processor())
.writer(writer())
.build();
}
Can't believe it couldn't find this issue for at least a few days.
Please do not respond with use mvn spring-boot:run or java -jar
I have the following config...
#Configuration
#EnableJpaRepositories("my.pkg.repository")
public class MyConfig {
#Autowired
DatasourceConfig config;
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("my.pkg.domain");
factory.setDataSource(config.getDatasource());
return factory;
}
#Bean
#Primary
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
}
But when I try to run via java -cp I get the following....
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [my/package/MyConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Class extends type annotation appeared on a non class target
What am I missing?
How am I building/running
mvn clean package -U
java -cp "target/lib.jar:resource/dir:other/jar/lib.jar" my.pkg.Application
Full Stacktrace
12:20:43.775 [main] ERROR org.springframework.boot.SpringApplication - Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [my/pkg/Config.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Class extends type annotation appeared on a non class target
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1794)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:405)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:140)
at my.pkg.Application.main(Application.java:19)
Caused by: java.lang.IllegalStateException: Class extends type annotation appeared on a non class target
at org.jboss.jandex.Indexer.processTypeAnnotation(Indexer.java:538)
at org.jboss.jandex.Indexer.processTypeAnnotations(Indexer.java:515)
at org.jboss.jandex.Indexer.processAttributes(Indexer.java:355)
at org.jboss.jandex.Indexer.processMethodInfo(Indexer.java:306)
at org.jboss.jandex.Indexer.index(Indexer.java:1598)
at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:64)
at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.handleEntry(ClassFileArchiveEntryHandler.java:52)
at org.hibernate.boot.archive.internal.JarFileBasedArchiveDescriptor.visitArchive(JarFileBasedArchiveDescriptor.java:147)
at org.hibernate.boot.archive.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:48)
at org.hibernate.boot.model.process.internal.ScanningCoordinator.coordinateScan(ScanningCoordinator.java:76)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:98)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:254)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:168)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:52)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1790)
... 14 common frames omitted
This is a jandex issue (the library that throws that Exception). I remember we had the same issue once, and there was a defect on github for that. It was fixed in 2.2.2.Final version - so you should upgrade to that.
The maven deps should be...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>[2.2.3.Final,)</version>
</dependency>
I am trying to configure two different configuration classes in my web application -- one that uses jdbc and another that uses hibernate.I defined my configuration classes as below:
#Profile("jdbc")
#Configuration
public class JdbcConfiguration {
...
}
#Profile("hibernate")
#Configuration
public class HibernateConfiguration {
...
}
I have two more main configuration classes.One is for services and one that defines some database infrastructure needed by both jdbc and hibernate configuration classes(for example,the data source bean).Here are the classes:
#Import({JdbcConfiguration.class, HibernateConfiguration.class})
#Configuration
#EnableTransactionManagement
#PropertySource("classpath:/db.properties")
public class DataAccessConfiguration {
...
}
#Configuration
#Import(DataAccessConfiguration.class)
#ComponentScan(basePackages = {"domain.validation","services"})
public class ServiceConfiguration {
private final UserDao userDao;
private final GroupDao groupDao;
private final TaskDao taskDao;
public ServiceConfiguration(UserDao userDao, GroupDao groupDao, TaskDao taskDao) {
this.userDao = userDao;
this.groupDao = groupDao;
this.taskDao = taskDao;
}
...
}
The thing i am trying to do is that the DataAccessConfiguration imports both jdbc and hibernate configuration.If jdbc profile is active,then only the beans in jdbc configuration should be created.Otherwise(if hibernate profile is active),hibernate's beans should be created.Then i import DataAccessConfig into ServiceConfiguration,which uses dao beans in the services.
I read in documentation that in order to activate a profile in web application,i need to define context parameter spring.profiles.active in my web.xml or add it programmatically to servletContext on boot.I did the former.Here is my web.xml
<web-app metadata-complete="false" version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" >
<display-name>Easy Do Web</display-name>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>jdbc</param-value>
</context-param>
</web-app>
I am not sure if this is important,but i configure my servletdispatcher by extending AbstractAnnotationConfigDispatcherServletInitializer .
The error that i am getting when i try to start my application is :
02-Jan-2020 13:29:46.070 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log 2 Spring WebApplicationInitializers detected on classpath
02-Jan-2020 13:29:48.973 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class [listeners.ContListener]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'serviceConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repository.UserDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:787)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:226)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:400)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
at org.springframework.context.support.AbstractApplicationContext.initMessageSource(AbstractApplicationContext.java:732)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:89)
at listeners.ContListener.contextInitialized(ContListener.java:37)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4685)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5146)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:717)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:690)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:705)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1728)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:289)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:456)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:405)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:289)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at com.sun.jmx.remote.security.MBeanServerAccessController.invoke(MBeanServerAccessController.java:468)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
at java.security.AccessController.doPrivileged(Native Method)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1408)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
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 sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repository.UserDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:874)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:778)
... 69 more
02-Jan-2020 13:29:48.974 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
02-Jan-2020 13:29:52.700 INFO [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Closing Spring root WebApplicationContext
Here is full jdbc configuration class(Same three dao beans are defined in hibernate configuration,except the classes are different):
#Profile("jdbc")
#Configuration
public class JdbcConfiguration {
private final DataSource dataSource;
public JdbcConfiguration(DataSource dataSource) {
this.dataSource = dataSource;
}
#Bean(name = "userDao")
public UserDao userDao(NamedParameterJdbcTemplate template){
return new UserDaoSpringJdbc(dataSource,template);
}
#Bean(name = "groupDao")
public GroupDao groupDao(UserDao userDao,NamedParameterJdbcTemplate template){
return new GroupDaoSpringJdbc(dataSource,userDao,template);
}
#Bean(name="taskDao")
public TaskDao taskDao(UserDao userDao,GroupDao groupDao,NamedParameterJdbcTemplate template){
return new TaskDaoSpringJdbc(dataSource,userDao,groupDao,template);
}
#Bean
NamedParameterJdbcTemplate template() {
return new NamedParameterJdbcTemplate(dataSource);
}
#Bean(name = "transactionManager")
PlatformTransactionManager jdbcTransactionManager() {
DataSourceTransactionManager manager = new DataSourceTransactionManager();
manager.setDataSource(dataSource);
return manager;
}
}
Your configuration looks fine even though we don't need #imported as it is very similar to in xml way of bean configuration.
According to stack trace,
repository.UserDao bean is not created in the spring context.
There is no UserDao bean defined in spring context to do so.
Solution is to create/register userDao bean in the spring context by annotating
the UserDao class with #Repository .
Have you used XML Configuration or Annotations? If you have Spring 4.0 Annotations, then you need to Autowire DAO Components.One more thing you need to keep in mind is
that Component Scan should include all the DAO Components you have scanned, otherwise, even though you may use Autowired, Still scanner won't be able to locate it in Scanning packages which you can define in XML or through Annotations.
The error was fixed.It was my assumption wrong,because i thought that spring would activate profile before my configuration class is created,but,apparently,spring activates the profile only when loading the already created configuration class to create the web application context.What i did was : i removed the import and added the two(jdbc and hibernate) configuration classes to be loaded with the service configuration class,thus spring loads jdbc and hibernate first and then the service.Hope this helps someone.
I have two data sources in my spring boot application. both declared like:
#Lazy
#Configuration
#EnableJpaRepositories(
basePackages = "com.nws.signer.db.dao",
entityManagerFactoryRef = "signerEntityManager",
transactionManagerRef = "signerTransactionManager"
)
#EnableTransactionManagement
public class SignerJPAConfig {
private Map<String, String> sig_db_props;
private String sig_url;
#Autowired
private VedProfiledPropsSource p;
#PostConstruct
public void init() {
sig_db_props = new HashMap<>();
sig_url =
String.format("jdbc:postgresql://%s:%s/%s", p.getSigDbHost(), p.getSigDbPort(), p.getSigDbName());
sig_db_props.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQL92Dialect");
sig_db_props.put("javax.persistence.jdbc.url", sig_url);
sig_db_props.put("javax.persistence.jdbc.user", p.getSigDbUser());
sig_db_props.put("javax.persistence.jdbc.password", p.getSigDbPassword());
sig_db_props.put("hibernate.connection.autocommit", "true");
sig_db_props.put("hibernate.cache.use_second_level_cache", "false");
sig_db_props.put("hibernate.hbm2ddl.auto", "update");
}
...
}
so I am using VedProfiledPropsSource which is #ConfigurationProperties with properties for specific profile used. after initializing jpaPropertyMap in postConstruct I am setting it to LocalContainerEntityManagerFactoryBean which is declared as a bean alongside with DataSource and PlatformTransactionManager. same for the other data source.
Now I want to use embedded-database-spring-test dependency:
<dependency>
<groupId>io.zonky.test</groupId>
<artifactId>embedded-database-spring-test</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
to bootstrap the embedded database for tests and connect my data sources to this database. the build machine doesn't have a database so I want to use this within the test scope.
my e2e test class starts with:
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
#ExtendWith(SpringExtension.class)
#Transactional
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {VedicaConfig.class})
#AutoConfigureMockMvc
#ActiveProfiles("mvntest")
#FlywayTest
#TestMethodOrder(MethodOrderer.OrderAnnotation.class)
#AutoConfigureEmbeddedDatabase(beanName = "signerJPAConfig")
public class RESTTest {
...
}
so I was thinking it will bootstrap the in-memory postgresql db and replace (by magic) the named data source anf flyway will apply migration scripts.
now I am missing/misunderstanding something as this is not happening and my data source configuration bean is still trying to connect to the database with credentials correctly red from profiled property file. and it fails with:
2019-10-07 00:05:53.785 ERROR 40358 --- [ prefetching-3] org.postgresql.Driver : Connection error:
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:245) ~[postgresql-42.2.2.jar:42.2.2]
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.2.2.jar:42.2.2]
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195) ~[postgresql-42.2.2.jar:42.2.2]
at org.postgresql.Driver.makeConnection(Driver.java:452) ~[postgresql-42.2.2.jar:42.2.2]
at org.postgresql.Driver.connect(Driver.java:254) ~[postgresql-42.2.2.jar:42.2.2]
at java.sql.DriverManager.getConnection(DriverManager.java:664) [na:1.8.0_66]
at java.sql.DriverManager.getConnection(DriverManager.java:208) [na:1.8.0_66]
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:154) [spring-jdbc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:145) [spring-jdbc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205) [spring-jdbc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169) [spring-jdbc-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.flywaydb.core.internal.jdbc.JdbcUtils.openConnection(JdbcUtils.java:56) [flyway-core-5.2.4.jar:na]
at org.flywaydb.core.internal.database.DatabaseFactory.createDatabase(DatabaseFactory.java:72) [flyway-core-5.2.4.jar:na]
at org.flywaydb.core.Flyway.execute(Flyway.java:1670) [flyway-core-5.2.4.jar:na]
at org.flywaydb.core.Flyway.migrate(Flyway.java:1356) [flyway-core-5.2.4.jar:na]
at io.zonky.test.db.flyway.DefaultFlywayDataSourceContext$FlywayDatabasePreparer.prepare(DefaultFlywayDataSourceContext.java:173) [embedded-database-spring-test-1.5.1.jar:na]
at io.zonky.test.db.provider.impl.ZonkyPostgresDatabaseProvider$DatabaseInstance$DatabaseTemplate.<init>(ZonkyPostgresDatabaseProvider.java:147) [embedded-database-spring-test-1.5.1.jar:na]
at io.zonky.test.db.provider.impl.ZonkyPostgresDatabaseProvider$DatabaseInstance$DatabaseTemplate.<init>(ZonkyPostgresDatabaseProvider.java:136) [embedded-database-spring-test-1.5.1.jar:na]
at io.zonky.test.db.provider.impl.ZonkyPostgresDatabaseProvider$DatabaseInstance$1.load(ZonkyPostgresDatabaseProvider.java:120) [embedded-database-spring-test-1.5.1.jar:na]
at io.zonky.test.db.provider.impl.ZonkyPostgresDatabaseProvider$DatabaseInstance$1.load(ZonkyPostgresDatabaseProvider.java:118) [embedded-database-spring-test-1.5.1.jar:na]
at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3542) [signer-1.0-SNAPSHOT.jar:na]
at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2323) [signer-1.0-SNAPSHOT.jar:na]
at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2286) [signer-1.0-SNAPSHOT.jar:na]
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2201) [signer-1.0-SNAPSHOT.jar:na]
at com.google.common.cache.LocalCache.get(LocalCache.java:3953) [signer-1.0-SNAPSHOT.jar:na]
at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3957) [signer-1.0-SNAPSHOT.jar:na]
at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4875) [signer-1.0-SNAPSHOT.jar:na]
at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4881) [signer-1.0-SNAPSHOT.jar:na]
at io.zonky.test.db.provider.impl.ZonkyPostgresDatabaseProvider$DatabaseInstance.getTemplate(ZonkyPostgresDatabaseProvider.java:133) [embedded-database-spring-test-1.5.1.jar:na]
at io.zonky.test.db.provider.impl.ZonkyPostgresDatabaseProvider.getDatabase(ZonkyPostgresDatabaseProvider.java:94) [embedded-database-spring-test-1.5.1.jar:na]
at io.zonky.test.db.provider.impl.PrefetchingDatabaseProvider$PrefetchingTask.lambda$new$0(PrefetchingDatabaseProvider.java:252) [embedded-database-spring-test-1.5.1.jar:na]
at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266) ~[na:1.8.0_66]
at java.util.concurrent.FutureTask.run(FutureTask.java) ~[na:1.8.0_66]
at io.zonky.test.db.provider.impl.PrefetchingDatabaseProvider$PrefetchingTask.run(PrefetchingDatabaseProvider.java:259) [embedded-database-spring-test-1.5.1.jar:na]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_66]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_66]
at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_66]
Caused by: java.net.ConnectException: Connection refused
please advice me what should I do in order to replace my real data source with embedded one?
Thanks
For me, this worked. If you have a Spring boot project with JPA (Entities and Repositories), you can create the following test:
#ExtendWith(SpringExtension.class)
#DataJpaTest(excludeAutoConfiguration = { LiquibaseAutoConfiguration.class })
#AutoConfigureEmbeddedDatabase
#ActiveProfiles("junit")
public class JpaTest {
#Autowired
private MyRepository repo;
#Test
public void create(){
...
}
Be sure to set the following properties:
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database=POSTGRESQL
How can I solve this error:
java.lang.reflect.InvocationTargetException: null
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.useContextualLobCreation(LobCreatorBuilderImpl.java:113) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.makeLobCreatorBuilder(LobCreatorBuilderImpl.java:54) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:271) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:861) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:888) [hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) [spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:388) [spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) [spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769) [spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706) [spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583) [spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) [spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) [spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) [spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) [spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1085) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:858) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at com.divergent.demo.DemoApplication.main(DemoApplication.java:12) ~[classes/:na]
Caused by: java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc.PgConnection.createClob() is not yet implemented.
at org.postgresql.Driver.notImplemented(Driver.java:683) ~[postgresql-42.2.1.jar:42.2.1]
at org.postgresql.jdbc.PgConnection.createClob(PgConnection.java:1252) ~[postgresql-42.2.1.jar:42.2.1]
... 44 common frames omitted
Add this property in your application.properties :
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
Reference :
https://github.com/spring-projects/spring-boot/issues/12007#issuecomment-369388646
This is an issue of Hibernate, as a workaround, you can use the following flag. Then set up the following config in your properties:
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
For Spring boot 2.x.x this flag simply disable contextual LOB creation, but if you really want to know the properly answer check UPDATE V1.
UPDATED V1
This was a Hibernate issue.
If you use Spring Boot latest version from 2.0.x until 2.1.x
includes Hibernate 5.3.10.final you can take a look here but this issue was fixed on Hibernate version 5.4.0.CR1 then you need to add that dependency or if it is possible the latest version:
For Gradle:
compile('org.hibernate:hibernate-core:5.4.2.Final')
For Maven:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.2.Final</version>
</dependency>
UPDATED V2 "SPRING BOOT 2.2.0.M(1-4)"
In addition Spring boot v2.2.0.Mx includes now Hibernate v5.4.x then this issue was fixed for these versions.
I had the similar issue.
I followed this solution and it worked for me
http://vkuzel.blogspot.com/2016/03/spring-boot-jpa-hibernate-atomikos.html
# Disable feature detection by this undocumented parameter. Check the org.hibernate.engine.jdbc.internal.JdbcServiceImpl.configure method for more details.
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
# Because detection is disabled you have to set correct dialect by hand.
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
Solved by using following Yaml configuration:
spring:
jpa:
properties:
hibernate:
jdbc:
lob:
non_contextual_creation: true
database-platform: org.hibernate.dialect.PostgreSQL9Dialect
Solved by adding hibernate.properties with
hibernate.jdbc.lob.non_contextual_creation=true
Other solutions with application.properties didn't work. This can be also done via XML hibernate.cfg.xml
Spring Boot version: 2.0.2.RELEASE
spring:
jpa:
properties:
hibernate:
temp:
use_jdbc_metadata_defaults: false
jdbc:
lob:
non_contextual_creation: true
with
use_jdbc_metadata_defaults: false
or
non_contextual_creation: true
two items work fine
Faced the same problem with Spring Boot version: 2.1.x.RELEASE too.
it worked with:
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
I was struggling with this stuff for a day.
Spring boot version 2.2.5
Postgres: 42.2.10
Version of Postgres on server: PostgreSQL 11.6 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.9.3, 64-bit
I was using Spring JPA data with Hibernate configuration. Using sessionFactory.
Hibernate configuration:
#Bean(name = "sessionFactory")
#Primary
public LocalSessionFactoryBean sessionFactory(){
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(assetHealthDataSource);
sessionFactoryBean.setMappingDirectoryLocations(new Resource[]{new ClassPathResource("mappings")});
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
Hibernate Properties:
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty(
"hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect");
hibernateProperties.setProperty(
"hibernate.jdbc.lob.non_contextual_creation", "true");
hibernateProperties.setProperty(
"hibernate.temp.use_jdbc_metadata_defaults", "false");
hibernateProperties.setProperty(
"hibernate.show_sql", environment.getProperty("assetHealthDataSource.hibernate.showSQL"));
hibernateProperties.setProperty(
"hibernate.format_sql", environment.getProperty("assetHealthDataSource.hibernate.formatSQL"));
hibernateProperties.setProperty(
"hibernate.transaction.auto_close_session", "false");
hibernateProperties.setProperty(
"hibernate.hibernate.connection.release_mode", "auto");
hibernateProperties.setProperty(
"hibernate.hikari.maximumPoolSize", "3");
hibernateProperties.setProperty(
"hibernate.default_schema", "MY_SCHEMA");
return hibernateProperties;
}
But everything was not working properly. Willing to see any suggestion that can help to solve this out.
Thank you very much.
For anyone searching for a Grails answer (3.3 and up), #Ashutosh's answer worked for me but what caught me out is in your application.yml file, you omit the spring.jpa.properties prefix. Add it to the hibernate section, where you're likely to have your dialect specified:
hibernate:
dialect: <your dialect>
jdbc:
lob:
non_contextual_creation: true
temp:
use_jdbc_metadata_defaults: false