c3p0 Connection Provider not set - spring

I am using spring an Hibernate and here is the Hibernate.properties
The problem is the Connection provider is not changing to c3p0ConnectionProvider even though there are c3p0 settings.THey are just loaded and nothing seems to be done with them.
hibernate.show_sql=true
hibernate.hbm2ddl.auto=validate
hibernate.c3p0.testConnectionOnCheckin = true
hibernate.c3p0.checkoutTimeout = 0
hibernate.c3p0.acquireIncrement=5
hibernate.c3p0.idleConnectionTestPeriod=3000
hibernate.c3p0.initialPoolSize=10
hibernate.c3p0.maxIdleTime=300
hibernate.c3p0.maxPoolSize=50
hibernate.c3p0.maxStatements=100
hibernate.c3p0.minPoolSize=5
hibernate.c3p0.testConnectionsOnCheckout=true
Here is the stack trace.
main INFO [org.springframework.web.context.ContextLoader] - Root WebApplicationContext: initialization started
main INFO [org.springframework.web.context.support.XmlWebApplicationContext] - Refreshing org.springframework.web.context.support.XmlWebApplicationContext#70074fd2: display name [Root WebApplicationContext]; startup date [Thu May 24 15:39:51 MDT 2012]; root of context hierarchy
main INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from ServletContext resource [/WEB-INF/core-data-annotation-context.xml]
main INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from ServletContext resource [/WEB-INF/core-data-datasource-context.xml]
main INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [META-INF/cxf/cxf.xml]
main INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [META-INF/cxf/cxf-extension-soap.xml]
main INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [META-INF/cxf/cxf-servlet.xml]
main INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from ServletContext resource [/WEB-INF/core-profile-datasource-context.xml]
main INFO [org.springframework.web.context.support.XmlWebApplicationContext] - Bean factory for application context [org.springframework.web.context.support.XmlWebApplicationContext#70074fd2]: org.springframework.beans.factory.support.DefaultListableBeanFactory#2f41eb55
main INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2f41eb55: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,pagingProviderHibernate,daoEager,dao,coreDataResourceLocator,cachingService,randomUtilService,randomWordGenerationService,placeHolderResolver,logsDbDao,subsetDbDao,profilesdbDao,resourceProfileLoaderNew,org.springframework.context.config.internalBeanConfigurerAspect,cxf,org.apache.cxf.bus.spring.BusApplicationListener,org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor,org.apache.cxf.bus.spring.Jsr250BeanPostProcessor,org.apache.cxf.bus.spring.BusExtensionPostProcessor,org.apache.cxf.resource.ResourceManager,org.apache.cxf.configuration.Configurer,org.apache.cxf.binding.BindingFactoryManager,org.apache.cxf.transport.DestinationFactoryManager,org.apache.cxf.transport.ConduitInitiatorManager,org.apache.cxf.wsdl.WSDLManager,org.apache.cxf.phase.PhaseManager,org.apache.cxf.workqueue.WorkQueueManager,org.apache.cxf.buslifecycle.BusLifeCycleManager,org.apache.cxf.endpoint.ServerRegistry,org.apache.cxf.endpoint.ServerLifeCycleManager,org.apache.cxf.endpoint.ClientLifeCycleManager,org.apache.cxf.transports.http.QueryHandlerRegistry,org.apache.cxf.endpoint.EndpointResolverRegistry,org.apache.cxf.headers.HeaderManager,org.apache.cxf.catalog.OASISCatalogManager,org.apache.cxf.endpoint.ServiceContractResolverRegistry,org.apache.cxf.binding.soap.SoapBindingFactory,org.apache.cxf.binding.soap.SoapTransportFactory,org.apache.cxf.binding.soap.customEditorConfigurer,org.apache.cxf.transport.servlet.ServletTransportFactory,infobutton-service,dataSource,sessionFactory,hibernateTemplate,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,subsetlogDao,logDao,profiledataSource,profilesessionFactory,profilehibernateTemplate,profiletransactionManager,profilesDao,pDao]; root of factory hierarchy
main INFO [org.springframework.beans.factory.config.PropertiesFactoryBean] - Loading properties file from ServletContext resource [/WEB-INF/datasource-mysql.properties]
main INFO [org.springframework.beans.factory.config.PropertiesFactoryBean] - Loading properties file from ServletContext resource [/WEB-INF/hibernate.properties]
main INFO [org.springframework.beans.factory.config.PropertiesFactoryBean] - Loading properties file from ServletContext resource [/WEB-INF/datasource-mysql.properties]
main INFO [org.hibernate.cfg.annotations.Version] - Hibernate Annotations 3.4.0.GA
main INFO [org.hibernate.cfg.Environment] - Hibernate 3.3.1.GA
main INFO [org.hibernate.cfg.Environment] - loaded properties from resource hibernate.properties: {hibernate.c3p0.maxStatements=100, hibernate.c3p0.maxIdleTime=300, hibernate.c3p0.idleConnectionTestPeriod=3000, hibernate.c3p0.testConnectionOnCheckin=true, hibernate.c3p0.acquireIncrement=5, hibernate.c3p0.initialPoolSize=10, hibernate.c3p0.maxPoolSize=50, hibernate.c3p0.minPoolSize=5, hibernate.hbm2ddl.auto=validate, hibernate.c3p0.testConnectionsOnCheckout=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.show_sql=true, hibernate.c3p0.checkoutTimeout=0}
main INFO [org.hibernate.cfg.Environment] - Bytecode provider name : javassist
main INFO [org.hibernate.cfg.Environment] - using JDK 1.4 java.sql.Timestamp handling
main INFO [org.hibernate.cfg.AnnotationBinder] - Binding entity from annotated class: com.asd.subsetdb.domain.Logs
main INFO [org.hibernate.cfg.annotations.EntityBinder] - Bind entity com.asd.subsetdb.domain.Logs on table logs
main INFO [org.hibernate.validator.Version] - Hibernate Validator 3.1.0.GA
main INFO [org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean] - Building new Hibernate SessionFactory
main INFO [org.hibernate.search.Version] - Hibernate Search 3.4.2.Final
main INFO [org.hibernate.connection.ConnectionProviderFactory] - Initializing connection provider:
org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider
main INFO [org.hibernate.cfg.SettingsFactory] - RDBMS: MySQL, version: 5.0.77
main INFO [org.hibernate.cfg.SettingsFactory] - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.17 ( Revision: ${bzr.revision-id} )
main INFO [org.hibernate.dialect.Dialect] - Using dialect: org.hibernate.dialect.MySQL5Dialect
main INFO [org.hibernate.transaction.TransactionFactoryFactory] - Transaction strategy: org.springframework.orm.hibernate3.SpringTransactionFactory
main INFO [org.hibernate.transaction.TransactionManagerLookupFactory] - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
main INFO [org.hibernate.cfg.SettingsFactory] - Automatic flush during beforeCompletion(): disabled
main INFO [org.hibernate.cfg.SettingsFactory] - Automatic session close at end of transaction: disabled
main INFO [org.hibernate.cfg.SettingsFactory] - JDBC batch size: 15
main INFO [org.hibernate.cfg.SettingsFactory] - JDBC batch updates for versioned data: disabled
main INFO [org.hibernate.cfg.SettingsFactory] - Scrollable result sets: enabled
main INFO [org.hibernate.cfg.SettingsFactory] - JDBC3 getGeneratedKeys(): enabled
main INFO [org.hibernate.cfg.SettingsFactory] - Connection release mode: auto
main INFO [org.hibernate.cfg.SettingsFactory] - Maximum outer join fetch depth: 2
main INFO [org.hibernate.cfg.SettingsFactory] - Default batch fetch size: 1
main INFO [org.hibernate.cfg.SettingsFactory] - Generate SQL with comments: disabled
main INFO [org.hibernate.cfg.SettingsFactory] - Order SQL updates by primary key: disabled
main INFO [org.hibernate.cfg.SettingsFactory] - Order SQL inserts for batching: disabled
main INFO [org.hibernate.cfg.SettingsFactory] - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
main INFO [org.hibernate.hql.ast.ASTQueryTranslatorFactory] - Using ASTQueryTranslatorFactory
main INFO [org.hibernate.cfg.SettingsFactory] - Query language substitutions: {}
main INFO [org.hibernate.cfg.SettingsFactory] - JPA-QL strict compliance: disabled
main INFO [org.hibernate.cfg.SettingsFactory] - Second-level cache: enabled
main INFO [org.hibernate.cfg.SettingsFactory] - Query cache: disabled
main INFO [org.hibernate.cfg.SettingsFactory] - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
main INFO [org.hibernate.cfg.SettingsFactory] - Optimize cache for minimal puts: disabled
main INFO [org.hibernate.cfg.SettingsFactory] - Structured second-level cache entries: disabled
main INFO [org.hibernate.cfg.SettingsFactory] - Echoing all SQL to stdout
main INFO [org.hibernate.cfg.SettingsFactory] - Statistics: disabled
main INFO [org.hibernate.cfg.SettingsFactory] - Deleted entity synthetic identifier rollback: disabled
main INFO [org.hibernate.cfg.SettingsFactory] - Default entity-mode: pojo
main INFO [org.hibernate.cfg.SettingsFactory] - Named query checking : enabled
main INFO [org.hibernate.impl.SessionFactoryImpl] - building session factory
main INFO [org.hibernate.impl.SessionFactoryObjectFactory] - Not binding factory to JNDI, no JNDI name configured
main INFO [org.hibernate.tool.hbm2ddl.SchemaValidator] - Running schema validator
main INFO [org.apache.jcs.engine.control.CompositeCacheConfigurator] - setting defaultElementAttributes to [ IS_LATERAL = true, IS_SPOOL = true, IS_REMOTE = true, IS_ETERNAL = false, MaxLifeSeconds = 7200, IdleTime = 1800, CreateTime = 1337895600422, LastAccessTime = 1337895600422, getTimeToLiveSeconds() = 7199, createTime = 1337895600422 ]

Fixed by adding this to the context/persistence.xml
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass"><value>com.mysql.jdbc.Driver</value></property>
<property name="jdbcUrl"><value>jdbc:mysql://localhost XXX</value>
</property>
<property name="user"><value>zzz</value></property>
<property name="password"><value>xxx</value></property>
</bean>
I am still not sure why it did not work without com.mchange.v2.c3p0.ComboPooledDataSource.

Related

Apache Camel: Help in understanding usage of SimpleScheduledRoutePolicy

Anybody has experience or know how to use SimpleScheduledRoutePolicy to manage a scheduler at runtime? To change the scheduler timing, suspend or resume. I tried using this in a spring boot project but it is not working as documented. Below is my Route configuration and a Test class I used to test this.
#Component
public class MyRouter extends RouteBuilder {
private static final Logger logger = LoggerFactory.getLogger(MyRouter.class);
#Override
public void configure() throws Exception {
SimpleScheduledRoutePolicy simpleScheduledRoutePolicy = new SimpleScheduledRoutePolicy();
long startTime = System.currentTimeMillis() + 5000l;
simpleScheduledRoutePolicy.setRouteStartDate(new Date(startTime));
simpleScheduledRoutePolicy.setRouteStartRepeatInterval(3000l);
simpleScheduledRoutePolicy.setRouteStartRepeatCount(3);
from("direct:myroute")
.routeId("myroute")
.routePolicy(simpleScheduledRoutePolicy)
.autoStartup(true)
.log(LoggingLevel.INFO, logger, "myroute invoked")
.to("mock:test");
}
}
Test class code
#RunWith(CamelSpringBootRunner.class)
#SpringBootTest
public class MyRouterTest {
#Autowired
private CamelContext camelContext;
#EndpointInject("mock:test")
MockEndpoint resultEndpoint;
#SneakyThrows
#Test
public void myRouteIsScheduledSuccessfully() {
resultEndpoint.expectedMessageCount(2);
Thread.sleep(7000);
resultEndpoint.assertIsSatisfied();
}
}
But I just gets below logs saying the scheduler started but it is not triggering every 3 seconds as configured in policy.
I tried to invoke the direct component from test method, still not working. Not sure where I am going wrong.
[INFO ] 2020-04-17 15:22:17.928 [main] MyRouterTest - Starting MyRouterTest on PPC11549 with PID 20892 (started by rmr in C:\Data\Telenet\Workspaces\atoms-event-engine)
[DEBUG] 2020-04-17 15:22:17.930 [main] MyRouterTest - Running with Spring Boot v2.2.6.RELEASE, Spring v5.2.5.RELEASE
[INFO ] 2020-04-17 15:22:17.932 [main] MyRouterTest - No active profile set, falling back to default profiles: default
[INFO ] 2020-04-17 15:22:19.634 [main] RepositoryConfigurationDelegate - Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
[INFO ] 2020-04-17 15:22:19.679 [main] RepositoryConfigurationDelegate - Finished Spring Data repository scanning in 36ms. Found 0 JDBC repository interfaces.
[INFO ] 2020-04-17 15:22:20.226 [main] PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.apache.camel.spring.boot.CamelAutoConfiguration' of type [org.apache.camel.spring.boot.CamelAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[INFO ] 2020-04-17 15:22:20.848 [main] HikariDataSource - HikariPool-1 - Starting...
[INFO ] 2020-04-17 15:22:21.437 [main] HikariDataSource - HikariPool-1 - Start completed.
[INFO ] 2020-04-17 15:22:22.602 [main] LRUCacheFactory - Detected and using LURCacheFactory: camel-caffeine-lrucache
[INFO ] 2020-04-17 15:22:24.082 [main] JobRepositoryFactoryBean - No database type set, using meta data indicating: H2
[INFO ] 2020-04-17 15:22:24.120 [main] SimpleJobLauncher - No TaskExecutor has been set, defaulting to synchronous executor.
[INFO ] 2020-04-17 15:22:24.485 [main] ThreadPoolTaskScheduler - Initializing ExecutorService 'taskScheduler'
[INFO ] 2020-04-17 15:22:24.695 [main] SpringBootRoutesCollector - Loading additional Camel XML routes from: classpath:camel/*.xml
[INFO ] 2020-04-17 15:22:24.698 [main] SpringBootRoutesCollector - Loading additional Camel XML rests from: classpath:camel-rest/*.xml
[INFO ] 2020-04-17 15:22:24.727 [main] MyRouterTest - Started MyRouterTest in 7.338 seconds (JVM running for 11.356)
[INFO ] 2020-04-17 15:22:24.729 [main] JobLauncherCommandLineRunner - Running default command line with: []
[INFO ] 2020-04-17 15:22:24.734 [main] CamelAnnotationsHandler - Setting shutdown timeout to [10 SECONDS] on CamelContext with name [camelContext].
[INFO ] 2020-04-17 15:22:24.815 [main] CamelSpringBootExecutionListener - #RunWith(CamelSpringBootRunner.class) before: class com.telenet.atoms.eventengine.camel.MyRouterTest.myRouteIsScheduledSuccessfully
[INFO ] 2020-04-17 15:22:24.817 [main] CamelSpringBootExecutionListener - Initialized CamelSpringBootRunner now ready to start CamelContext
[INFO ] 2020-04-17 15:22:24.818 [main] CamelAnnotationsHandler - Starting CamelContext with name [camelContext].
[INFO ] 2020-04-17 15:22:24.902 [main] DefaultManagementStrategy - JMX is enabled
[INFO ] 2020-04-17 15:22:25.308 [main] AbstractCamelContext - Apache Camel 3.2.0 (CamelContext: camel-1) is starting
[INFO ] 2020-04-17 15:22:25.438 [main] QuartzComponent - Create and initializing scheduler.
[INFO ] 2020-04-17 15:22:25.442 [main] QuartzComponent - Setting org.quartz.scheduler.jmx.export=true to ensure QuartzScheduler(s) will be enlisted in JMX.
[INFO ] 2020-04-17 15:22:25.483 [main] StdSchedulerFactory - Using default implementation for ThreadExecutor
[INFO ] 2020-04-17 15:22:25.487 [main] SimpleThreadPool - Job execution threads will use class loader of thread: main
[INFO ] 2020-04-17 15:22:25.511 [main] SchedulerSignalerImpl - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
[INFO ] 2020-04-17 15:22:25.511 [main] QuartzScheduler - Quartz Scheduler v.2.3.2 created.
[INFO ] 2020-04-17 15:22:25.516 [main] RAMJobStore - RAMJobStore initialized.
[INFO ] 2020-04-17 15:22:25.528 [main] QuartzScheduler - Scheduler meta-data: Quartz Scheduler (v2.3.2) 'DefaultQuartzScheduler-camel-1' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
[INFO ] 2020-04-17 15:22:25.528 [main] StdSchedulerFactory - Quartz scheduler 'DefaultQuartzScheduler-camel-1' initialized from an externally provided properties instance.
[INFO ] 2020-04-17 15:22:25.528 [main] StdSchedulerFactory - Quartz scheduler version: 2.3.2
[INFO ] 2020-04-17 15:22:25.529 [main] AbstractCamelContext - StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
[INFO ] 2020-04-17 15:22:25.623 [main] AbstractCamelContext - Route: myroute started and consuming from: direct://myroute
[INFO ] 2020-04-17 15:22:25.625 [main] AbstractCamelContext - Route: orderfault started and consuming from: direct://orderfault
[INFO ] 2020-04-17 15:22:25.637 [main] AbstractCamelContext - Total 2 routes, of which 2 are started
[INFO ] 2020-04-17 15:22:25.638 [main] AbstractCamelContext - Apache Camel 3.2.0 (CamelContext: camel-1) started in 0.329 seconds
[INFO ] 2020-04-17 15:22:25.663 [main] ScheduledRoutePolicy - Scheduled trigger: triggerGroup-myroute.trigger-START-myroute for action: START on route myroute
[INFO ] 2020-04-17 15:22:25.663 [main] ScheduledRoutePolicy - Scheduled trigger: triggerGroup-orderfault.trigger-START-orderfault for action: START on route orderfault
[INFO ] 2020-04-17 15:22:25.664 [main] QuartzComponent - Starting scheduler.
[INFO ] 2020-04-17 15:22:25.665 [main] QuartzScheduler - Scheduler DefaultQuartzScheduler-camel-1_$_NON_CLUSTERED started.
[INFO ] 2020-04-17 15:22:33.101 [main] MockEndpoint - Asserting: mock://test is satisfied
[INFO ] 2020-04-17 15:22:43.134 [main] MyRouterTest - ********************************************************************************
[INFO ] 2020-04-17 15:22:43.135 [main] MyRouterTest - Testing done: myRouteIsScheduledSuccessfully(com.telenet.atoms.eventengine.camel.MyRouterTest)
[INFO ] 2020-04-17 15:22:43.136 [main] MyRouterTest - Took: 17.469 seconds (17469 millis)
[INFO ] 2020-04-17 15:22:43.136 [main] MyRouterTest - ********************************************************************************
[INFO ] 2020-04-17 15:22:43.137 [main] CamelSpringBootExecutionListener - #RunWith(CamelSpringBootRunner.class) after: class com.telenet.atoms.eventengine.camel.MyRouterTest.myRouteIsScheduledSuccessfully
java.lang.AssertionError: mock://test Received message count. Expected: <2> but was: <0>
The SimpleScheduledRoutePolicy works as expected - it starts your Camel Route and that's what it is for: starting and stopping routes.
Because of your test, I guess that you want to have a Scheduler endpoint that triggers messages in a configured interval. For this you have to use Camel Timer, Camel Scheduler or Camel Quartz.
Since your route does not contain any of these, there is simply no scheduler that can be started.
To create a scheduler that (after waiting initially 5 seconds) fires every 3 seconds you can use for example this:
from("scheduler://foo?initialDelay=5s&delay=3s")...
Change at runtime (added due to comment)
The Camel Quartz component obviously uses the Quartz scheduler and Quartz provides a JMX access. So if you want to change the scheduler this is probably your best option.
To start and stop routes at runtime you should have a look at Camel Controlbus.

Spring transactions - isolation and propagation understanding

I am exploring spring transactions and after going through the spring docs and the following link i still have few questions. If I have a parent method with Propogation.REQUIRED which is calling 3 methods with Propogation.REQUIRES_NEW as follows:
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public Contact saveContactInSteps(Contact contact, String newFirstName, String newLastName, Date bDate) throws Exception {
contact.setFirstName(newFirstName);
try {
updateContactFirstName(contact);
} catch (Exception e) {
LOG.error("Contact first name could not be saved !!");
e.printStackTrace();
throw e;
}
contact.setLastName(newLastName);
try {
updateContactLastName(contact);
} catch (Exception e) {
LOG.error("Contact Last name could not be saved !!");
e.printStackTrace();
throw e;
}
contact.setBirthDate(bDate);
updateContactBday(contact);
return contact;
}
public Contact saveById(Contact contact) {
sessionFactory.getCurrentSession().saveOrUpdate(contact);
LOG.info("Contact " + contact + " saved successfully");
return contact;
}
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
public Contact updateContactFirstName(Contact contact) throws Exception {
throw new Exception("Cannot update first name");
//sessionFactory.getCurrentSession().saveOrUpdate(contact);
//LOG.info("Contact First name saved successfully");
//return contact;
}
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
public Contact updateContactLastName(Contact contact) throws Exception {
throw new Exception("Cannot update last name");
//sessionFactory.getCurrentSession().saveOrUpdate(contact);
//LOG.info("Contact " + contact + " saved successfully");
//return contact;
}
//#Transactional(isolation=Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
public Contact updateContactBday(Contact contact) {
sessionFactory.getCurrentSession().saveOrUpdate(contact);
LOG.info("Contact Birth Date saved successfully");
return contact;
}
Whenever i process the parent method i.e. saveContactInSteps, even the last name is getting updated in database. I am not sure how that is happening. If i throw the exception from first child method nothing gets updated. Is it because of the fact that i am setting the attributes i.e. names and birthdate in the parent method ? Even if i am setting the attributes in the parent method, i am not letting the parent method complete as well. Does the isolation level play any part here ? I believe it's for concurrent transactions ? Is there something i am missing ?
EDIT 1:
After going through the article i did realize what i was missing. I needed AOP proxies in place which i have added as follows:
<aop:config>
<aop:pointcut
expression="execution(* org.pack.spring.transactions.ContactService.*(..))"
id="updateOperation" />
<aop:advisor pointcut-ref="updateOperation" advice-ref="saveUpdateAdvice" />
</aop:config>
<tx:advice id="saveUpdateAdvice">
<tx:attributes>
<tx:method name="update*" propagation="REQUIRES_NEW" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
Log output is as follows:
01:23:57.535 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.save' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.550 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0'
01:23:57.552 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'saveUpdateAdvice'
01:23:57.552 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean 'saveUpdateAdvice'
01:23:57.552 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Eagerly caching bean 'saveUpdateAdvice' to allow for resolving potential circular references
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean '(inner bean)#56ac5c80'
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
01:23:57.553 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.557 [main] DEBUG o.s.t.i.NameMatchTransactionAttributeSource - Adding transactional method [update*] with attribute [PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT,-Exception]
01:23:57.557 [main] DEBUG o.s.t.i.NameMatchTransactionAttributeSource - Adding transactional method [save*] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-Exception]
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
01:23:57.557 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.558 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean '(inner bean)#56ac5c80'
01:23:57.558 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'saveUpdateAdvice'
01:23:57.558 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'saveUpdateAdvice'
01:23:57.568 [main] DEBUG o.s.a.a.a.AspectJAwareAdvisorAutoProxyCreator - Creating implicit proxy for bean 'springTxContactService' with 0 common interceptors and 3 specific interceptors
01:23:57.575 [main] DEBUG o.s.aop.framework.CglibAopProxy - Creating CGLIB proxy: target source is SingletonTargetSource for target object [org.pack.ch9.spring.transactions.hibernate.home.ContactService#598260a6]
01:23:57.654 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.save(org.pack.ch9.spring.transactions.hibernate.home.Contact)
01:23:57.654 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.saveContactInSteps' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.655 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.saveContactInSteps(org.pack.ch9.spring.transactions.hibernate.home.Contact,java.lang.String,java.lang.String,java.util.Date) throws java.lang.Exception
01:23:57.655 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.findAll' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
01:23:57.656 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public java.util.List org.pack.ch9.spring.transactions.hibernate.home.ContactService.findAll()
01:23:57.656 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.findById' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
01:23:57.656 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.findById(java.lang.Long)
01:23:57.657 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.saveById' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.657 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.saveById(org.pack.ch9.spring.transactions.hibernate.home.Contact)
01:23:57.657 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.updateContactFirstName' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.657 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.updateContactFirstName(org.pack.ch9.spring.transactions.hibernate.home.Contact) throws java.lang.Exception
01:23:57.658 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.updateContactLastName' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.658 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.updateContactLastName(org.pack.ch9.spring.transactions.hibernate.home.Contact) throws java.lang.Exception
01:23:57.658 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.updateContactBday' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.658 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.pack.ch9.spring.transactions.hibernate.home.Contact org.pack.ch9.spring.transactions.hibernate.home.ContactService.updateContactBday(org.pack.ch9.spring.transactions.hibernate.home.Contact)
01:23:57.659 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.setSessionFactory' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.660 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public void org.pack.ch9.spring.transactions.hibernate.home.ContactService.setSessionFactory(org.hibernate.SessionFactory)
01:23:57.661 [main] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'ContactService.getSessionFactory' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:57.661 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public org.hibernate.SessionFactory org.pack.ch9.spring.transactions.hibernate.home.ContactService.getSessionFactory()
01:23:57.661 [main] DEBUG o.s.aop.framework.CglibAopProxy - Found 'equals' method: public boolean java.lang.Object.equals(java.lang.Object)
01:23:57.662 [main] DEBUG o.s.aop.framework.CglibAopProxy - Unable to apply any optimisations to advised method: public java.lang.String java.lang.Object.toString()
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.event.internalEventListenerFactory'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'saveUpdateAdvice'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'sessionFactory'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'hibernateProperties'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor'
01:23:57.698 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor'
01:23:57.699 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionalEventListenerFactory'
01:23:57.699 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
01:23:57.746 [main] DEBUG o.s.c.s.GenericXmlApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor#21d1b321]
01:23:57.747 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
01:23:57.750 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
01:23:57.752 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'springTxContactService'
01:23:57.755 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
01:23:57.762 [main] DEBUG o.s.o.h.HibernateTransactionManager - Creating new transaction with name [org.pack.ch9.spring.transactions.hibernate.home.ContactService.findById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
01:23:57.962 [main] DEBUG o.s.o.h.HibernateTransactionManager - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
01:23:57.964 [main] DEBUG o.s.o.h.HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
01:23:57.965 [main] DEBUG o.s.j.d.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/springorm]
01:23:57.977 [main] DEBUG o.s.jdbc.datasource.DataSourceUtils - Setting JDBC Connection [com.mysql.jdbc.JDBC4Connection#2a685eba] read-only
01:23:57.983 [main] DEBUG o.s.o.h.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [com.mysql.jdbc.JDBC4Connection#2a685eba]
Hibernate: select distinct contact0_.ID as ID1_0_0_, contacttel1_.ID as ID1_2_1_, hobby3_.HOBBY_ID as HOBBY_ID1_3_2_, contact0_.BIRTH_DATE as BIRTH_DA2_0_0_, contact0_.FIRST_NAME as FIRST_NA3_0_0_, contact0_.LAST_NAME as LAST_NAM4_0_0_, contact0_.VERSION as VERSION5_0_0_, contacttel1_.CONTACT_ID as CONTACT_5_2_1_, contacttel1_.TEL_NUMBER as TEL_NUMB2_2_1_, contacttel1_.TEL_TYPE as TEL_TYPE3_2_1_, contacttel1_.VERSION as VERSION4_2_1_, contacttel1_.CONTACT_ID as CONTACT_5_2_0__, contacttel1_.ID as ID1_2_0__, hobbies2_.CONTACT_ID as CONTACT_2_1_1__, hobbies2_.HOBBY_ID as HOBBY_ID1_1_1__ from contact contact0_ left outer join contact_tel_detail contacttel1_ on contact0_.ID=contacttel1_.CONTACT_ID left outer join contact_hobby_detail hobbies2_ on contact0_.ID=hobbies2_.CONTACT_ID left outer join hobby hobby3_ on hobbies2_.HOBBY_ID=hobby3_.HOBBY_ID where contact0_.ID=?
01:23:58.099 [main] DEBUG o.s.o.h.HibernateTransactionManager - Initiating transaction commit
01:23:58.101 [main] DEBUG o.s.o.h.HibernateTransactionManager - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[org.pack.ch9.spring.transactions.hibernate.home.Contact#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#7]],collectionKeys=[CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.contactTelDetails#6], CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.hobbies#6]]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
01:23:58.103 [main] DEBUG o.s.jdbc.datasource.DataSourceUtils - Resetting read-only flag of JDBC Connection [com.mysql.jdbc.JDBC4Connection#2a685eba]
01:23:58.103 [main] DEBUG o.s.o.h.HibernateTransactionManager - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[org.pack.ch9.spring.transactions.hibernate.home.Contact#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#7]],collectionKeys=[CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.contactTelDetails#6], CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.hobbies#6]]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] after transaction
01:23:58.117 [main] DEBUG o.s.o.h.HibernateTransactionManager - Creating new transaction with name [org.pack.ch9.spring.transactions.hibernate.home.ContactService.saveContactInSteps]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
01:23:58.117 [main] DEBUG o.s.o.h.HibernateTransactionManager - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
01:23:58.117 [main] DEBUG o.s.o.h.HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
01:23:58.117 [main] DEBUG o.s.j.d.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/springorm]
01:23:58.127 [main] DEBUG o.s.o.h.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [com.mysql.jdbc.JDBC4Connection#1daf3b44]
01:23:58.127 [main] DEBUG o.s.o.h.HibernateTransactionManager - Found thread-bound Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
01:23:58.127 [main] DEBUG o.s.o.h.HibernateTransactionManager - Participating in existing transaction
01:23:58.127 [main] ERROR o.p.c.s.t.h.home.ContactService - Contact First name could not be saved !!
01:23:58.127 [main] ERROR o.p.c.s.t.h.home.ContactService - Contact Last name could not be saved !!
01:23:58.137 [main] INFO o.p.c.s.t.h.home.ContactService - Contact Birth Date saved successfully
01:23:58.138 [main] DEBUG o.s.o.h.HibernateTransactionManager - Initiating transaction commit
01:23:58.138 [main] DEBUG o.s.o.h.HibernateTransactionManager - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[org.pack.ch9.spring.transactions.hibernate.home.Contact#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#6], EntityKey[org.pack.ch9.spring.transactions.hibernate.home.ContactTelDetail#7]],collectionKeys=[CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.contactTelDetails#6], CollectionKey[org.pack.ch9.spring.transactions.hibernate.home.Contact.hobbies#6]]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
Note - I have removed the #Transactional annotations from the methods as i am relying on proxy to achieve the same.
From the logs, it seems that the proxies are getting created but again as pointed out in the comment, will the 3 methods invoked from saveContactInSteps not have a transaction against them as mentioned in the documentation :
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with #Transactional. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. #PostConstruct
Is there a way to get around this ? Is AspectJ the only solution ?

spring boot tempory h2 database table empty in junit4 test

I am using Spring Boot 1.2.5 and want to do some JUnit4 testing. I have an Eclipse project that contains the test. During initializiation a temporay H2 database is created. I have a schema.xml and data.xml. The initialization is fine, but later three of 5 tables are empty.
First I had the database created by Spring boot. No code from my side, just the XML in the resources folder. This runs without any problems. Then I found that in the test three of the five tables are empty. The schema still exists, but not data.
I then changed to manual creation of the H2 database/datasource bean and in the same method I checked if all records are present. This made no difference in the test results. I could only show that just after creation the database is populated as expected. It seems that during bean creation and JUnit test some routine is doing a delete on three specific tables.
package de.unit4.financials;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.test.jdbc.JdbcTestUtils;
#SpringBootApplication
public class JUnitConfig {
Logger logger = LogManager.getLogger();
#Bean
public DataSource getDataSource() {
DataSource dataSource = null;
if (dataSource == null) {
dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).setName("FanUtilDB")
.addScript("classpath:schema.sql").addScript("classpath:data.sql").build();
}
logger.info("Datasource "+dataSource);
testDB(new JdbcTemplate(dataSource));
return dataSource;
}
public void testDB(JdbcTemplate jdbcTemplate) {
countTableRows("oas_company", jdbcTemplate);
countTableRows("oas_agm", jdbcTemplate);
countTableRows("oas_agmlist", jdbcTemplate);
countTableRows("com_usr", jdbcTemplate);
countTableRows("com_capab", jdbcTemplate);
}
private void countTableRows(String name, JdbcTemplate jdbcTemplate) {
int anzahl = JdbcTestUtils.countRowsInTable(jdbcTemplate, name);
logger.info(name + " = " + anzahl);
}
}
This is the output:
08:58:16.007 [main] INFO Datasource org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory$EmbeddedDataSourceProxy#60094a13 || de.unit4.financials.JUnitConfig getDataSource 54
08:58:16.197 [main] INFO oas_company = 28 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.199 [main] INFO oas_agm = 2 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.201 [main] INFO oas_agmlist = 2 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.203 [main] INFO com_usr = 52 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.205 [main] INFO com_capab = 17 || de.unit4.financials.JUnitConfig countTableRows 74
Later the JUnit test is run and it gives me this result:
08:58:19.099 [main] INFO Datasource org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory$EmbeddedDataSourceProxy#60094a13 || de.unit4.financials.periods.CurrentPeriodDBFactory getCurrentPeriod 63
08:58:19.127 [main] INFO oas_company = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.128 [main] INFO oas_agm = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.128 [main] INFO oas_agmlist = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.129 [main] INFO com_usr = 52 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.130 [main] INFO com_capab = 17 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
The DataSource object seems to be the same, but the record count is different. During the test, the first three are empty.
Here is the test:
package de.unit4.financials;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.jdbc.JdbcTestUtils;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = JUnitConfig.class)
public class FinancialsUtilApplicationTests {
static Logger logger = LogManager.getLogger();
#Autowired
JdbcTemplate jdbcTemplate;
#Test
public void contextLoads() {
}
#Test
public void testDB() {
countTableRows("oas_company");
countTableRows("oas_agm");
countTableRows("oas_agmlist");
countTableRows("com_usr");
countTableRows("com_capab");
}
/**
* #param name
*/
private void countTableRows(String name) {
int anzahl = JdbcTestUtils.countRowsInTable(jdbcTemplate, name);
logger.info(name + " = " + anzahl);
}
}
Here is the full console output:
08:58:12.555 [main] DEBUG o.s.t.c.j.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class de.unit4.financials.periods.PeriodRangeTest].
08:58:12.581 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating TestContextBootstrapper from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
08:58:12.607 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - Found explicit ContextLoader class [org.springframework.boot.test.SpringApplicationContextLoader] for context configuration attributes [ContextConfigurationAttributes#32e6e9c3 declaringClass = 'de.unit4.financials.periods.PeriodRangeTest', classes = '{class de.unit4.financials.JUnitConfig}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.boot.test.SpringApplicationContextLoader']
08:58:12.618 [main] DEBUG o.s.t.c.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.627 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - #TestExecutionListeners is not present for class [de.unit4.financials.periods.PeriodRangeTest]: using defaults.
08:58:12.644 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
08:58:12.672 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
08:58:12.688 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#73ad2d6, org.springframework.test.context.support.DirtiesContextTestExecutionListener#7085bdee, org.springframework.test.context.transaction.TransactionalTestExecutionListener#1ce92674, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#5700d6b1]
08:58:12.692 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.694 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.718 [main] DEBUG o.s.t.c.j.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class de.unit4.financials.periods.CurrentPeriodDBFactoryTest].
08:58:12.718 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating TestContextBootstrapper from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
08:58:12.720 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - Found explicit ContextLoader class [org.springframework.boot.test.SpringApplicationContextLoader] for context configuration attributes [ContextConfigurationAttributes#4566e5bd declaringClass = 'de.unit4.financials.periods.CurrentPeriodDBFactoryTest', classes = '{class de.unit4.financials.JUnitConfig}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.boot.test.SpringApplicationContextLoader']
08:58:12.721 [main] DEBUG o.s.t.c.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [de.unit4.financials.periods.CurrentPeriodDBFactoryTest]
08:58:12.722 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - #TestExecutionListeners is not present for class [de.unit4.financials.periods.CurrentPeriodDBFactoryTest]: using defaults.
08:58:12.727 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
08:58:12.729 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
08:58:12.729 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#2d928643, org.springframework.test.context.support.DirtiesContextTestExecutionListener#5025a98f, org.springframework.test.context.transaction.TransactionalTestExecutionListener#49993335, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#20322d26]
08:58:12.729 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.CurrentPeriodDBFactoryTest]
08:58:12.730 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.CurrentPeriodDBFactoryTest]
08:58:12.733 [main] DEBUG o.s.t.c.j.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class de.unit4.financials.periods.PeriodTest].
08:58:12.734 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating TestContextBootstrapper from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
08:58:12.736 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - Found explicit ContextLoader class [org.springframework.boot.test.SpringApplicationContextLoader] for context configuration attributes [ContextConfigurationAttributes#64bf3bbf declaringClass = 'de.unit4.financials.periods.PeriodTest', classes = '{class de.unit4.financials.JUnitConfig}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.boot.test.SpringApplicationContextLoader']
08:58:12.737 [main] DEBUG o.s.t.c.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [de.unit4.financials.periods.PeriodTest]
08:58:12.738 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - #TestExecutionListeners is not present for class [de.unit4.financials.periods.PeriodTest]: using defaults.
08:58:12.743 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
08:58:12.744 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
08:58:12.745 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#544fe44c, org.springframework.test.context.support.DirtiesContextTestExecutionListener#31610302, org.springframework.test.context.transaction.TransactionalTestExecutionListener#71318ec4, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#21213b92]
08:58:12.745 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodTest]
08:58:12.745 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodTest]
08:58:12.752 [main] DEBUG o.s.t.c.j.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class de.unit4.financials.FinancialsUtilApplicationTests].
08:58:12.753 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating TestContextBootstrapper from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
08:58:12.762 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - Found explicit ContextLoader class [org.springframework.boot.test.SpringApplicationContextLoader] for context configuration attributes [ContextConfigurationAttributes#3108bc declaringClass = 'de.unit4.financials.FinancialsUtilApplicationTests', classes = '{class de.unit4.financials.JUnitConfig}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.boot.test.SpringApplicationContextLoader']
08:58:12.762 [main] DEBUG o.s.t.c.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [de.unit4.financials.FinancialsUtilApplicationTests]
08:58:12.763 [main] DEBUG o.s.t.c.s.DefaultTestContextBootstrapper - #TestExecutionListeners is not present for class [de.unit4.financials.FinancialsUtilApplicationTests]: using defaults.
08:58:12.769 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
08:58:12.770 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
08:58:12.770 [main] INFO o.s.t.c.s.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#335eadca, org.springframework.test.context.support.DirtiesContextTestExecutionListener#210366b4, org.springframework.test.context.transaction.TransactionalTestExecutionListener#eec5a4a, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#2b2948e2]
08:58:12.770 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.FinancialsUtilApplicationTests]
08:58:12.770 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.FinancialsUtilApplicationTests]
08:58:12.786 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.787 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.788 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.789 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.790 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.790 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.793 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [de.unit4.financials.periods.PeriodRangeTest]
08:58:12.793 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [de.unit4.financials.periods.PeriodRangeTest]
08:58:13.324 [main] DEBUG o.s.t.c.s.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext#6193932a testClass = PeriodRangeTest, testInstance = de.unit4.financials.periods.PeriodRangeTest#647fd8ce, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#159f197 testClass = PeriodRangeTest, locations = '{}', classes = '{class de.unit4.financials.JUnitConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.boot.test.SpringApplicationContextLoader', parent = [null]]]].
08:58:13.395 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
08:58:13.398 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
08:58:13.398 [main] DEBUG o.s.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
08:58:13.401 [main] DEBUG o.s.core.env.StandardEnvironment - Adding [integrationTest] PropertySource with search precedence immediately lower than [systemEnvironment]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.2.5.RELEASE)
2015-07-20 08:58:13.766 INFO 8552 --- [ main] d.u.financials.periods.PeriodRangeTest : Starting PeriodRangeTest on gsender with PID 8552 (C:\Users\gsender\Documents\workspace-libs\FinancialsUtility\target\test-classes started by GSender in C:\Users\gsender\Documents\workspace-libs\FinancialsUtility)
2015-07-20 08:58:13.812 INFO 8552 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#524d6d96: startup date [Mon Jul 20 08:58:13 CEST 2015]; root of context hierarchy
2015-07-20 08:58:15.572 INFO 8552 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Creating embedded database 'FanUtilDB'
2015-07-20 08:58:15.823 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [schema.sql]
2015-07-20 08:58:15.851 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [schema.sql] in 28 ms.
2015-07-20 08:58:15.851 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [data.sql]
2015-07-20 08:58:15.990 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [data.sql] in 139 ms.
08:58:16.007 [main] INFO Datasource org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory$EmbeddedDataSourceProxy#60094a13 || de.unit4.financials.JUnitConfig getDataSource 54
08:58:16.197 [main] INFO oas_company = 28 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.199 [main] INFO oas_agm = 2 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.201 [main] INFO oas_agmlist = 2 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.203 [main] INFO com_usr = 52 || de.unit4.financials.JUnitConfig countTableRows 74
08:58:16.205 [main] INFO com_capab = 17 || de.unit4.financials.JUnitConfig countTableRows 74
2015-07-20 08:58:16.271 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from URL [file:/C:/Users/gsender/Documents/workspace-libs/FinancialsUtility/target/test-classes/schema.sql]
2015-07-20 08:58:16.285 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from URL [file:/C:/Users/gsender/Documents/workspace-libs/FinancialsUtility/target/test-classes/schema.sql] in 14 ms.
2015-07-20 08:58:16.289 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from URL [file:/C:/Users/gsender/Documents/workspace-libs/FinancialsUtility/target/test-classes/data.sql]
2015-07-20 08:58:16.391 INFO 8552 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from URL [file:/C:/Users/gsender/Documents/workspace-libs/FinancialsUtility/target/test-classes/data.sql] in 101 ms.
2015-07-20 08:58:16.555 INFO 8552 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2015-07-20 08:58:16.590 INFO 8552 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2015-07-20 08:58:16.682 INFO 8552 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {4.3.10.Final}
2015-07-20 08:58:16.684 INFO 8552 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2015-07-20 08:58:16.686 INFO 8552 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2015-07-20 08:58:16.979 INFO 8552 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2015-07-20 08:58:17.136 INFO 8552 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2015-07-20 08:58:17.424 INFO 8552 --- [ main] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory
2015-07-20 08:58:18.153 INFO 8552 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2015-07-20 08:58:18.178 INFO 8552 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2015-07-20 08:58:19.063 INFO 8552 --- [ main] d.u.financials.periods.PeriodRangeTest : Started PeriodRangeTest in 5.659 seconds (JVM running for 7.356)
08:58:19.099 [main] INFO Datasource org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory$EmbeddedDataSourceProxy#60094a13 || de.unit4.financials.periods.CurrentPeriodDBFactory getCurrentPeriod 63
08:58:19.127 [main] INFO oas_company = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.128 [main] INFO oas_agm = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.128 [main] INFO oas_agmlist = 0 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.129 [main] INFO com_usr = 52 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
08:58:19.130 [main] INFO com_capab = 17 || de.unit4.financials.FinancialsUtilApplicationTests countTableRows 40
2015-07-20 08:58:19.134 INFO 8552 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#524d6d96: startup date [Mon Jul 20 08:58:13 CEST 2015]; root of context hierarchy
2015-07-20 08:58:19.386 INFO 8552 --- [ Thread-1] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2015-07-20 08:58:19.387 INFO 8552 --- [ Thread-1] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2015-07-20 08:58:19.398 INFO 8552 --- [ Thread-1] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
For Table creation I use (example):
drop table IF EXISTS oas_company;
CREATE TABLE IF NOT EXISTS oas_company (
code varchar(12) NOT NULL,
code_cs int NOT NULL,
For data inserts I use:
delete from oas_agm;
INSERT INTO oas_agm(code, tstamp, name, sname, adddate, deldate, moddate, usrname)
VALUES('U4SW-JUNIT-1', 1, 'Account Test Entwicklung', 'debit', '2015-07-15 00:00:00.0', NULL, '2015-07-15 15:31:39.0', 'INSTALL');
Thanks for any help on this confusing result.
I found the solution: Hibernate recreates the tables after initialisation (by Spring Boot). I added spring.jpa.hibernate.ddl-auto=none to application.properties and the problem was gone.
This is the first time this happened in a project. It is also unclear why only three out of five tables are recreated. At first I assumed it was due to an "old" database file, but then I switched from H2 to HSQL and the problem stayed. An error from Hibernate showed me the path to solution (unable to delete...).

Spring boot taking long time to start

I have a spring boot application where it listens to a RabbitMQ queue.
The problem is when i run my application it hangs at particular step at
hibernate and it takes around 10 minutes to further continue.
Below is where it hangs
INFO [] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
INFO [] org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 3338 ms
INFO [] org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor - Initializing ExecutorService 'metricsExecutor'
INFO [] org.springframework.boot.context.embedded.ServletRegistrationBean - Mapping servlet: 'dispatcherServlet' to [/]
INFO [] org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'metricFilter' to: [/*]
INFO [] org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'characterEncodingFilter' to: [/*]
INFO [] org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'webRequestLoggingFilter' to: [/*]
INFO [] org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
INFO [] org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'applicationContextIdFilter' to: [/*]
[main] INFO [] org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'default'
[main] INFO [] org.hibernate.jpa.internal.util.LogHelper - HHH000204: Processing PersistenceUnitInfo [
name: default
...]
[main] INFO [] org.hibernate.Version - HHH000412: Hibernate Core {4.3.7.Final}
[main] INFO [] org.hibernate.cfg.Environment - HHH000205: Loaded properties from resource hibernate.properties: {hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect, hibernate.show_sql=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.format_sql=true, hibernate.ejb.naming_strategy=org.hibernate.cfg.DefaultNamingStrategy}
[main] INFO [] org.hibernate.cfg.Environment - HHH000021: Bytecode provider name : javassist
[main] INFO [] org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Below is the timing info
2015-07-08 09:31:16,714 [main] INFO [] org.hibernate.Version - HHH000412: Hibernate Core {4.3.7.Final}
2015-07-08 09:31:16,717 [main] INFO [] org.hibernate.cfg.Environment - HHH000205: Loaded properties from resource hibernate.properties: {hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect, hibernate.show_sql=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.format_sql=true, hibernate.ejb.naming_strategy=org.hibernate.cfg.DefaultNamingStrategy}
2015-07-08 09:31:16,717 [main] INFO [] org.hibernate.cfg.Environment - HHH000021: Bytecode provider name : javassist
2015-07-08 09:31:16,895 [main] INFO [] org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
In the above line it hangs for 8 min, and then it generates the below log waiting for any message.
15-07-14 15:36:22,917 [main] INFO [] com.test.myApp.reporting.service.Application
- Starting Application on hyd-rupakular-m.local with PID 654 (/Users/myUser/code/myRepo/target/classes started by rupakulr in /Users/myuser/myRepo/xyzabc)
2015-07-14 15:36:22,966 [main] INFO [] org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5fa0d903: startup date [Tue Jul 14 15:36:22 IST 2015]; root of context hierarchy
2015-07-14 15:36:24,023 [main] INFO [] org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [spring-integration-context.xml]
2015-07-14 15:36:24,332 [main] INFO [] org.springframework.beans.factory.config.PropertiesFactoryBean - Loading properties file from URL [jar:file:/Users/rupakulr/.m2/repository/org/springframework/integration/spring-integration-core/4.1.2.RELEASE/spring-integration-core-4.1.2.RELEASE.jar!/META-INF/spring.integration.default.properties]
2015-07-14 15:45:09,646 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/env],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2015-07-14 15:45:09,646 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/metrics/{name:.*}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2015-07-14 15:45:09,646 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/metrics],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2015-07-14 15:45:09,647 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/mappings],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2015-07-14 15:45:09,647 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/trace],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2015-07-14 15:45:09,647 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/shutdown],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.ShutdownMvcEndpoint.invoke()
2015-07-14 15:45:09,647 [main] INFO [] org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping - Mapped "{[/manage/beans],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2015-07-14 15:45:09,700 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
2015-07-14 15:45:09,708 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Bean with name 'org.springframework.integration.channel.interceptor.WireTap#0' has been autodetected for JMX exposure
2015-07-14 15:45:09,708 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Bean with name 'org.springframework.integration.channel.interceptor.WireTap#1' has been autodetected for JMX exposure
2015-07-14 15:45:09,709 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Bean with name 'org.springframework.integration.config.RouterFactoryBean#0' has been autodetected for JMX exposure
2015-07-14 15:45:09,712 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Located managed bean 'org.springframework.integration.channel.interceptor.WireTap#0': registering with JMX server as MBean [org.springframework.integration.channel.interceptor:name=org.springframework.integration.channel.interceptor.WireTap#0,type=WireTap]
2015-07-14 15:45:09,726 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Located managed bean 'org.springframework.integration.channel.interceptor.WireTap#1': registering with JMX server as MBean [org.springframework.integration.channel.interceptor:name=org.springframework.integration.channel.interceptor.WireTap#1,type=WireTap]
2015-07-14 15:45:09,730 [main] INFO [] org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Located managed bean 'org.springframework.integration.config.RouterFactoryBean#0': registering with JMX server as MBean [org.springframework.integration.router:name=org.springframework.integration.config.RouterFactoryBean#0,type=HeaderValueRouter]
2015-07-14 15:45:09,745 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Registering beans for JMX exposure on startup
2015-07-14 15:45:09,749 [main] INFO [] org.springframework.context.support.DefaultLifecycleProcessor - Starting beans in phase -2147483648
2015-07-14 15:45:09,750 [main] INFO [] org.springframework.context.support.DefaultLifecycleProcessor - Starting beans in phase 0
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {router} as a subscriber to the 'reporting-dealer-compliance-dealer-list-channel' channel
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.reporting-dealer-compliance-dealer-list-channel' has 1 subscriber(s).
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started org.springframework.integration.config.ConsumerEndpointFactoryBean#0
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {object-to-json-transformer} as a subscriber to the 'reporting-dealer-compliance-dealer-compliance-json-channel' channel
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.reporting-dealer-compliance-dealer-compliance-json-channel' has 1 subscriber(s).
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started org.springframework.integration.config.ConsumerEndpointFactoryBean#1
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {logging-channel-adapter:logging-channel.adapter} as a subscriber to the 'logging-channel' channel
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.logging-channel' has 1 subscriber(s).
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started logging-channel.adapter
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {stream:outbound-channel-adapter(character):std-out-channel.adapter} as a subscriber to the 'std-out-channel' channel
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.std-out-channel' has 1 subscriber(s).
2015-07-14 15:45:09,751 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started std-out-channel.adapter
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.amqp.inbound.AmqpInboundGateway - started org.springframework.integration.amqp.inbound.AmqpInboundGateway#0
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {amqp:outbound-channel-adapter:invalidMessageChannelAdapter} as a subscriber to the 'invalid-message-channel' channel
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.invalid-message-channel' has 2 subscriber(s).
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started invalidMessageChannelAdapter
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {service-activator} as a subscriber to the 'failed-channel' channel
2015-07-14 15:45:10,968 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.failed-channel' has 1 subscriber(s).
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started org.springframework.integration.config.ConsumerEndpointFactoryBean#2
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {amqp:outbound-channel-adapter:failedMessageChannelAdapter} as a subscriber to the 'failed-channel' channel
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.failed-channel' has 2 subscriber(s).
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started failedMessageChannelAdapter
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.handler.MessageHandlerChain - started org.springframework.integration.handler.MessageHandlerChain#0
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {chain} as a subscriber to the 'reporting-dealer-compliance-inbound-channel' channel
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.reporting-dealer-compliance-inbound-channel' has 1 subscriber(s).
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started org.springframework.integration.config.ConsumerEndpointFactoryBean#3
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.handler.MessageHandlerChain - started org.springframework.integration.handler.MessageHandlerChain#1
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {chain} as a subscriber to the 'prepare-csv' channel
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.channel.DirectChannel - Channel 'application:8204.prepare-csv' has 1 subscriber(s).
2015-07-14 15:45:10,969 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started org.springframework.integration.config.ConsumerEndpointFactoryBean#4
2015-07-14 15:45:10,971 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'requestMappingEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=requestMappingEndpoint]
2015-07-14 15:45:10,979 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'environmentEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=environmentEndpoint]
2015-07-14 15:45:10,986 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'healthEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=healthEndpoint]
2015-07-14 15:45:10,992 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'beansEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=beansEndpoint]
2015-07-14 15:45:10,997 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'infoEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=infoEndpoint]
2015-07-14 15:45:11,003 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'metricsEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=metricsEndpoint]
2015-07-14 15:45:11,009 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'traceEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=traceEndpoint]
2015-07-14 15:45:11,014 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'dumpEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=dumpEndpoint]
2015-07-14 15:45:11,020 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'autoConfigurationAuditEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=autoConfigurationAuditEndpoint]
2015-07-14 15:45:11,026 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'shutdownEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=shutdownEndpoint]
2015-07-14 15:45:11,032 [main] INFO [] org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter - Located managed bean 'configurationPropertiesReportEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=configurationPropertiesReportEndpoint]
2015-07-14 15:45:11,037 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2015-07-14 15:45:11,037 [main] INFO [] org.springframework.integration.channel.PublishSubscribeChannel - Channel 'application:8204.errorChannel' has 1 subscriber(s).
2015-07-14 15:45:11,037 [main] INFO [] org.springframework.integration.endpoint.EventDrivenConsumer - started _org.springframework.integration.errorLogger
2015-07-14 15:45:11,037 [main] INFO [] org.springframework.context.support.DefaultLifecycleProcessor - Starting beans in phase 2147483647
2015-07-14 15:45:11,089 [main] INFO [] org.apache.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8204"]
2015-07-14 15:45:11,095 [main] INFO [] org.apache.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8204"]
2015-07-14 15:45:11,100 [main] INFO [] org.apache.tomcat.util.net.NioSelectorPool - Using a shared selector for servlet write/read
2015-07-14 15:45:11,112 [main] INFO [] org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat started on port(s): 8204 (http)
2015-07-14 15:45:11,115 [main] INFO [] com.test.myApp.reporting.service.Application - Started Application in 528.444 seconds (JVM running for 529.101)
we are experiencing a lot of problem when developing our app, every time we make some changes we have to wait 8 min to test our changes.
In case you are running your application on Linux, try to add this property to the java commandline:
-Djava.security.egd=file:/dev/./urandom
E.g.:
/usr/bin/java -Xmx75m -Djava.security.egd=file:/dev/./urandom -jar app.jar
I had a similar problem, although it did not take 8 minutes but only around 3 to start the application, and this solved it for me.
I think I faced with the similar issue. In my case time to start was proportional to the database size. And the entire problem was that hibernate (we use hibernate-core-5.0.2-Final) loads full metadata from DB just for obtaining Dialect value.
We now use following property to disable:
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
But make sure you specify 'spring.jpa.database-platform' value correct.
Here is related part of JdbcEnvironmentInitiator.java file:
#Override
public JdbcEnvironment initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
final DialectFactory dialectFactory = registry.getService( DialectFactory.class );
// 'hibernate.temp.use_jdbc_metadata_defaults' is a temporary magic value.
// The need for it is intended to be alleviated with future development, thus it is
// not defined as an Environment constant...
//
// it is used to control whether we should consult the JDBC metadata to determine
// certain Settings default values; it is useful to *not* do this when the database
// may not be available (mainly in tools usage).
boolean useJdbcMetadata = ConfigurationHelper.getBoolean(
"hibernate.temp.use_jdbc_metadata_defaults",
configurationValues,
true
);
if ( useJdbcMetadata ) {
final JdbcConnectionAccess jdbcConnectionAccess = buildJdbcConnectionAccess( configurationValues, registry );
try {
final Connection connection = jdbcConnectionAccess.obtainConnection();
try {
final DatabaseMetaData dbmd = connection.getMetaData();
if ( log.isDebugEnabled() ) {
log.debugf(
"Database ->\n"
+ " name : %s\n"
+ " version : %s\n"
+ " major : %s\n"
+ " minor : %s",
dbmd.getDatabaseProductName(),
dbmd.getDatabaseProductVersion(),
dbmd.getDatabaseMajorVersion(),
dbmd.getDatabaseMinorVersion()
);
log.debugf(
"Driver ->\n"
+ " name : %s\n"
+ " version : %s\n"
+ " major : %s\n"
+ " minor : %s",
dbmd.getDriverName(),
dbmd.getDriverVersion(),
dbmd.getDriverMajorVersion(),
dbmd.getDriverMinorVersion()
);
log.debugf( "JDBC version : %s.%s", dbmd.getJDBCMajorVersion(), dbmd.getJDBCMinorVersion() );
}
Dialect dialect = dialectFactory.buildDialect(
configurationValues,
new DialectResolutionInfoSource() {
#Override
public DialectResolutionInfo getDialectResolutionInfo() {
try {
return new DatabaseMetaDataDialectResolutionInfoAdapter( connection.getMetaData() );
}
catch ( SQLException sqlException ) {
throw new HibernateException(
"Unable to access java.sql.DatabaseMetaData to determine appropriate Dialect to use",
sqlException
);
}
}
}
);
return new JdbcEnvironmentImpl(
registry,
dialect,
dbmd
);
}
catch (SQLException e) {
log.unableToObtainConnectionMetadata( e.getMessage() );
}
finally {
try {
jdbcConnectionAccess.releaseConnection( connection );
}
catch (SQLException ignore) {
}
}
}
catch (Exception e) {
log.unableToObtainConnectionToQueryMetadata( e.getMessage() );
}
}
// if we get here, either we were asked to not use JDBC metadata or accessing the JDBC metadata failed.
return new JdbcEnvironmentImpl( registry, dialectFactory.buildDialect( configurationValues, null ) );
}

XAER_OUTSIDE Exception - Spring 4.0.3 - Hibernate 4.1.12 - JTA - Websphere 8 - DB2

EDIT - I have checked this combinations so it seems there's something wrong with Hibernate 4:
Spring 4 + JPA + Hibernate 4 -> Exception
Spring 4 + Hibernate 4 -> Exception
Spring 4 + JPA + Hibernate 3 -> OK
Spring 4 + Hibernate 3 -> OK
Spring 3 + JPA - Hibernate 4 -> Exception
Spring 3 + JPA - Hibernate 3 -> OK
Spring 3 + Hibernate 3 -> OK
I have recently upgraded an application from Spring 3.2/Hibernate 3.6.10 to Spring 4.0.3 + Hibernate 4.1.12. My environment is IBM Websphere 8.0.0.7 and DB2 and the application is configured to use a XA Datasource.
The point is that at the first database call (subsequent calls are always OK) I am getting this error:
#Transactional(readOnly = true)
public Foo loadFoo(int id) {
LOG.debug("load {}", id);
FooEntity fe = fooDAO.findOne(id);
...
}
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'fooRestController'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'globalControllerAdvice'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'org.springframework.transaction.interceptor.TransactionInterceptor#0'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=false
org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource DEBUG - Adding transactional method 'findOne' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=true
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Opening JPA EntityManager
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - Skipping JTA sync registration due to auto join checking
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - successfully registered Synchronization
org.hibernate.ejb.AbstractEntityManagerImpl DEBUG - Looking for a JTA transaction to join
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Registering transaction synchronization for JPA EntityManager
org.hibernate.loader.Loader DEBUG - Loading entity: [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtaining JDBC connection
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtained JDBC connection
DSRA0304E: XAException occurred. XAException contents and details are: "".
DSRA0302E: XAException occurred. Error code is: XAER_OUTSIDE (-9). Exception is: XAER_OUTSIDE
J2CA0027E: An exception occurred while invoking start on an XA Resource Adapter from DataSource jdbc/LOCDBD1_XA, within transaction ID {XidImpl: formatId(57415344), gtrid_length(36), bqual_length(54),
data(0000014517a4c063000000015e7f81b4c90865e6b88e167905e5d2ed67f44ed6409cba5c0000014517a4c063000000015e7f81b4c90865e6b88e167905e5d2ed67f44ed6409cba5c000000010000000000000000000000000001)} : com.ibm.db2.jcc.c.zh: XAER_OUTSIDE
Caused by: javax.transaction.RollbackException: XAResource working outside transaction
at com.ibm.tx.jta.impl.RegisteredResources.startRes(RegisteredResources.java:1019)
at com.ibm.ws.tx.jta.RegisteredResources.enlistResource(RegisteredResources.java:1113)
at com.ibm.ws.tx.jta.TransactionImpl.enlistResource(TransactionImpl.java:2214)
at com.ibm.tx.jta.impl.EmbeddableTranManagerSet.enlist(EmbeddableTranManagerSet.java:150)
at com.ibm.ejs.j2c.XATransactionWrapper.enlist(XATransactionWrapper.java:727)
... 140 more
Caused by: com.ibm.db2.jcc.c.zh: XAER_OUTSIDE
at com.ibm.db2.jcc.b.bc.a(bc.java:1651)
at com.ibm.db2.jcc.b.bc.start(bc.java:1530)
at com.ibm.ws.rsadapter.spi.WSRdbXaResourceImpl.start(WSRdbXaResourceImpl.java:1525)
at com.ibm.ejs.j2c.XATransactionWrapper.start(XATransactionWrapper.java:1475)
at com.ibm.ws.Transaction.JTA.JTAResourceBase.start(JTAResourceBase.java:153)
at com.ibm.tx.jta.impl.RegisteredResources.startRes(RegisteredResources.java:1002)
... 144 more
This is the log trace of the second and successful call :
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'fooRestController'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'globalControllerAdvice'
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=false
org.springframework.beans.factory.support.DefaultListableBeanFactory DEBUG - Returning cached instance of singleton bean 'transactionManager'
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Invoking WebSphere UOW action: type=1, join=true
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Opening JPA EntityManager
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - Skipping JTA sync registration due to auto join checking
org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl DEBUG - successfully registered Synchronization
org.hibernate.ejb.AbstractEntityManagerImpl DEBUG - Looking for a JTA transaction to join
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Registering transaction synchronization for JPA EntityManager
org.hibernate.loader.Loader DEBUG - Loading entity: [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtaining JDBC connection
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Obtained JDBC connection
org.hibernate.loader.Loader DEBUG - Result set row: 0
org.hibernate.loader.Loader DEBUG - Result row: EntityKey[com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.internal.TwoPhaseLoad DEBUG - Resolving associations for [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.internal.TwoPhaseLoad DEBUG - Done materializing entity [com.mycompany.spring4.entity.FooEntity#17027]
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Releasing JDBC connection
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Released JDBC connection
org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler DEBUG - HHH000163: Logical connection releasing its physical connection
org.hibernate.loader.Loader DEBUG - Done entity load
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Returned from WebSphere UOW action: type=1, join=true
org.springframework.orm.jpa.EntityManagerFactoryUtils DEBUG - Closing JPA EntityManager
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl DEBUG - Aggressively releasing JDBC connection
org.springframework.transaction.jta.WebSphereUowTransactionManager DEBUG - Returned from WebSphere UOW action: type=1, join=false
The relevant part of my cfg is:
<bean id="mainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="mainPersistenceUnit"/>
<property name="jtaDataSource" ref="mainDataSource"/>
<property name="packagesToScan" ref="packages-mainEntityManagerFactory"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform</prop>
<prop key="hibernate.current_session_context_class">jta</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory</prop>
</props>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
<tx:annotation-driven order="0" />
<bean name="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager">
<property name="allowCustomIsolationLevels" value="true" />
</bean>
Any idea why it fails the first time it's called?
The problem solved by itself upgrading to Spring 4.1.6 and Hibernate 4.2.19. I guess it was a Hibernate-related issue.

Resources