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.
Related
Spring Boot version: 2.4.0Reactor netty now supports Unix Domain Sockets while initializing server.
I am trying to custmoize Spring Boot HttpServer to use unix domain socket instead of http port using
#Configuration
public class NettyConfig {
#Bean
public NettyReactiveWebServerFactory factory() {
NettyReactiveWebServerFactory factory = new NettyReactiveWebServerFactory();
factory.setServerCustomizers(Collections.singletonList(new NettyServerCustomizer() {
#Override
public HttpServer apply(HttpServer httpServer) {
return httpServer.bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"));
}
}));
return factory;
}
}
But application is unable to start with given stacktrace:
13:05:36.706 ERROR [restartedMain] SpringApplication.reportFailure:856 : Application run failed
org.springframework.context.ApplicationContextException: Failed to start bean 'webServerStartStop'; nested exception is java.lang.UnsupportedOperationException
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181)
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54)
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356)
at java.base/java.lang.Iterable.forEach(Iterable.java:75)
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155)
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:942)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:591)
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:63)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:326)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1309)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1298)
at com.avis.biverve.EntryPoint.main(EntryPoint.java:25)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.UnsupportedOperationException
at reactor.netty.DisposableServer.port(DisposableServer.java:69)
at org.springframework.boot.web.embedded.netty.NettyWebServer.getPort(NettyWebServer.java:193)
at org.springframework.boot.web.embedded.netty.NettyWebServer.start(NettyWebServer.java:109)
at org.springframework.boot.web.reactive.context.WebServerManager.start(WebServerManager.java:54)
at org.springframework.boot.web.reactive.context.WebServerStartStopLifecycle.start(WebServerStartStopLifecycle.java:40)
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178)
... 20 more
This issue is fixed in Spring Boot version 2.4.2
https://github.com/spring-projects/spring-boot/issues/24529
In order to use multiple database in Springboot application having Axon framework.
I used #EnableJpaRepositories after which I started getting following error
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: TokenEntry is not mapped [SELECT te.segment FROM TokenEntry te WHERE te.processorName = :processorName ORDER BY te.segment ASC]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:725)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:816)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
at sun.reflect.GeneratedMethodAccessor107.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:366)
at com.sun.proxy.$Proxy150.createQuery(Unknown Source)
at sun.reflect.GeneratedMethodAccessor107.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:314)
at com.sun.proxy.$Proxy150.createQuery(Unknown Source)
at org.axonframework.eventhandling.tokenstore.jpa.JpaTokenStore.fetchSegments(JpaTokenStore.java:194)
at org.axonframework.eventhandling.TrackingEventProcessor$WorkerLauncher.run(TrackingEventProcessor.java:1195)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: TokenEntry is not mapped [SELECT te.segment FROM TokenEntry te WHERE te.processorName = :processorName ORDER BY te.segment ASC]
at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:220)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:162)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:604)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:716)
... 15 common frames omitted
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: TokenEntry is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:169)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
... 21 common frames omitted
Following is the way I enabled JPA repositories
#Data
#Configuration
#EnableScheduling
#ConfigurationProperties(prefix = "spring.datasource")
#EnableJpaRepositories(
basePackages = {"com.mypackage","org.axonframework.eventhandling.tokenstore.jpa"},
entityManagerFactoryRef = "postgresEntityManager",
transactionManagerRef = "postgresTransactionManager")}
)
public class PostgresConfiguration {
Interesting, I'd assume this to work out of the box really.
Are you using Spring Boot by any chance #tijo? To be honest I am assuming not, but it does give me a suggestion.
Axon Framework uses the #RegisterDefaultEntities annotation to register the required entities automatically for you when you're using the axon-springboot-starter. You can see this being done on the JpaAutoConfiguration class.
What's being done there is the following:
#RegisterDefaultEntities(packages = {
"org.axonframework.eventhandling.tokenstore",
"org.axonframework.modelling.saga.repository.jpa"
})
public class JpaAutoConfiguration { ... }
Would you mind checking whether that works? Main difference I see in your config is that you're only using the "org.axonframework.eventhandling.tokenstorejpa" base package.
Let us know whether this does the trick!
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
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.