Spring test properties file overriden by main properties file - java

I have a project where I am setting up Spring test configuration, for the DAO (JPA) layer. My test config gets loaded but only after the main config, especially properties file. So instead of trying to connect to HSQLDB, my test connects to the "real" PostGre database.
Here is my test class :
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({"/spring-dao-test.xml"})
#Transactional
#Rollback
public class EnseigneDaoTest {
#Autowired
EnseigneDao enseigneDao;
public EnseigneDaoTest() {
// TODO Auto-generated constructor stub
}
#Test
public void testFindById() {
Enseigne enseigne = enseigneDao.findById(Enseigne.class, "4");
assertNotNull(enseigne);
assertEquals("Auchan should have ID 4", "Auchan", enseigne.getLibelle());
}
}
Here is the spring-dao-test.xml :
<!-- Searches for entities in this package, no need for Persistence.xml -->
<context:component-scan base-package="fr.xxx.ddc.dao" />
<context:property-placeholder
location="classpath:fr/insee/config/ddc-dao-test.properties"/>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="fr.xxx.ddc.model" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaDialect" ref="jpaDialect" />
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${fr.xxx.ddc.hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.max_fetch_depth">${fr.xxx.ddc.hibernate.max_fetch_depth}</prop>
<prop key="hibernate.default_batch_fetch_size">${fr.xxx.ddc.hibernate.default_batch_fetch_size}</prop>
<prop key="hibernate.id.new_generator_mappings">true</prop>
</props>
</property>
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="HSQL"/>
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${fr.xxx.database.ddc.driverClassName}"/>
<property name="url" value="${fr.xxx.database.ddc.url}" />
<property name="username" value="${fr.xxx.database.ddc.username}" />
<property name="password" value="${fr.xxx.database.ddc.password}" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
The ddc-dao-test.properties :
fr.xxx.ddc.hibernate.schema=ddc
fr.xxx.ddc.hibernate.max_fetch_depth=3
fr.xxx.ddc.hibernate.default_batch_fetch_size=15
fr.xxx.ddc.hibernate.hbm2ddl.auto=create
fr.xxx.ddc.hibernate.show_sql=false
#Driver H2 pour test
fr.xxx.database.ddc.driverClassName=org.hsqldb.Driver
fr.xxx.database.ddc.url=hsqldb:mem:
fr.xxx.database.ddc.username=sa
fr.xxx.database.ddc.password=
and I get the following log :
09:24:40.262 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [class path resource [fr/insee/config/ddc-dao.properties]] PropertySource with lowest search precedence
[...]
09:24:41.717 [main] INFO org.springframework.context.support.PropertySourcesPlaceholderConfigurer - Loading properties file from class path resource [fr/insee/config/ddc-dao-test.properties]
09:24:41.718 [main] DEBUG org.springframework.core.env.MutablePropertySources - Adding [localProperties] PropertySource with lowest search precedence
09:24:41.719 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Searching for key 'fr.xxx.ddc.hibernate.max_fetch_depth' in [environmentProperties]
09:24:41.719 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Searching for key 'fr.xxx.ddc.hibernate.max_fetch_depth' in [systemProperties]
09:24:41.720 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Searching for key 'fr.xxx.ddc.hibernate.max_fetch_depth' in [systemEnvironment]
09:24:41.720 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Searching for key 'fr.xxx.ddc.hibernate.max_fetch_depth' in [class path resource [fr/insee/config/ddc-dao.properties]]
09:24:41.720 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Found key 'fr.xxx.ddc.hibernate.max_fetch_depth' in [class path resource [fr/insee/config/ddc-dao.properties]] with type [String] and value '3'
09:24:41.721 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Found key 'fr.xxx.ddc.hibernate.max_fetch_depth' in [environmentProperties] with type [String] and value '3'
How do I get rid of the ddc-dao.properties ? It seems there are some concepts I didn't get.
Thanks in advance.
Thanks a lot.

Finally I managed to do it.
The problem is indeed the
<context:component-scan base-package="fr.xxx.ddc.dao" />
loading DaoConfiguration.java, itself loading the main .properties file.
I needed to exclude the class, which is done this way :
<context:component-scan base-package="fr.xxx.ddc.dao" >
<context:exclude-filter type="assignable" expression="fr.xxx.ddc.dao.config.DaoConfiguration"/>
</context:component-scan>
and then my DaoConfiguration is no more loaded, nor the ddc-dao-config.xml or the ddc-dao.properties. My in-memory db is used as the log shows :
org.h2.jdbc.JdbcSQLException: Table "ENSEIGNES" not found
Hope this helps someone.

Related

How to configure Hibernate 5 SessionFactoryBean for using HikariCP?

Where should I configure connection pool for spring + hibernate application?
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="edu.khai.education.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:tcp://localhost/~/test"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
I want to use org.hibernate.hikaricp.internal.HikariCPConnectionProvider and I don't have a problem to configure it in Hibernate application, but I don't know how to integrate it with Spring.
Spring uses DataSource bean to create a lot of infrastructure code e.g. JdbcTemplate or Spring Data JPA #Repository.
Replace the current data source implementation org.apache.commons.dbcp2.BasicDataSource with the com.zaxxer.hikari.HikariDataSource class. Change the current properties to match the HikariCP configuration.

Unable to access TransactionManager or UserTransaction after updating to Hibernate 5

I just updated from Hibernate 4.2.19 to Hibernate 5.1.2. Of course, little it is to say that things are not going as planned. After solving several issues (among which JOIN FETCH had to be replaced by JOIN), I now run into the next issue:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'idolConfig': Invocation of init method failed; nested exception is org.hibernate.resource.transaction.backend.jta.internal.JtaPlatformInaccessibleException: Unable to access TransactionManager or UserTransaction to make physical transaction delegate
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1575)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
[...]
Caused by: org.hibernate.resource.transaction.backend.jta.internal.JtaPlatformInaccessibleException: Unable to access TransactionManager or UserTransaction to make physical transaction delegate
at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl.makePhysicalTransactionDelegate(JtaTransactionCoordinatorImpl.java:229)
at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl.getTransactionDriverControl(JtaTransactionCoordinatorImpl.java:203)
at org.hibernate.engine.transaction.internal.TransactionImpl.<init>(TransactionImpl.java:36)
at org.hibernate.internal.AbstractSessionImpl.getTransaction(AbstractSessionImpl.java:313)
at org.hibernate.internal.SessionImpl.<init>(SessionImpl.java:281)
at org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1326)
at org.hibernate.jpa.internal.EntityManagerImpl.internalGetSession(EntityManagerImpl.java:133)
[...]
The logs show that the JtaPlatform could not be loaded:
2016-11-14 15:34:22,853 DEBUG .o.j.EntityManagerFactoryUtils - Line {272} Opening JPA EntityManager
2016-11-14 15:34:22,973 DEBUG e.t.j.p.i.JtaPlatformInitiator - Line {42} No JtaPlatform was specified, checking resolver
2016-11-14 15:34:22,973 DEBUG e.t.j.p.i.JtaPlatformInitiator - Line {42} No JtaPlatform was specified, checking resolver
2016-11-14 15:34:22,974 DEBUG i.JtaPlatformResolverInitiator - Line {33} No JtaPlatformResolver was specified, using default [org.hibernate.engine.transaction.jta.platform.internal.StandardJtaPlatformResolver]
2016-11-14 15:34:22,974 DEBUG i.JtaPlatformResolverInitiator - Line {33} No JtaPlatformResolver was specified, using default [org.hibernate.engine.transaction.jta.platform.internal.StandardJtaPlatformResolver]
2016-11-14 15:34:22,992 DEBUG .i.StandardJtaPlatformResolver - Line {101} Could not resolve JtaPlatform, using default [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2016-11-14 15:34:22,992 DEBUG .i.StandardJtaPlatformResolver - Line {101} Could not resolve JtaPlatform, using default [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2016-11-14 15:34:22,994 DEBUG .JtaTransactionCoordinatorImpl - Line {258} JtaPlatform#retrieveTransactionManager returned null
2016-11-14 15:34:22,994 DEBUG .JtaTransactionCoordinatorImpl - Line {258} JtaPlatform#retrieveTransactionManager returned null
2016-11-14 15:34:22,995 DEBUG .JtaTransactionCoordinatorImpl - Line {223} Unable to access TransactionManager, attempting to use UserTransaction instead
2016-11-14 15:34:22,995 DEBUG .JtaTransactionCoordinatorImpl - Line {223} Unable to access TransactionManager, attempting to use UserTransaction instead
2016-11-14 15:34:22,995 DEBUG .JtaTransactionCoordinatorImpl - Line {241} JtaPlatform#retrieveUserTransaction returned null
2016-11-14 15:34:22,995 DEBUG .JtaTransactionCoordinatorImpl - Line {241} JtaPlatform#retrieveUserTransaction returned null
I do not have a persistence.xml file. Here is my spring.xml:
<bean id="entityManagerFactoryEcli"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="commonUnit" />
<property name="dataSource" ref="dataSourceEcli" />
<property name="packagesToScan"
value="org.my.common.portal.domain,eu.cec.justice.common.domain.entity" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="javax.persistence.transactionType">jta</prop>
<prop key="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.WeblogicTransactionManagerLookup</prop>
<prop key="hibernate.current_session_context_class">org.hibernate.context.internal.JTASessionContext</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.my.common.util.ECLICommonEhCacheRegionFactory</prop>
</props>
</property>
</bean>
<bean id="entityManagerFactoryCommon"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="portalUnit" />
<property name="dataSource" ref="dataSourceCommon" />
<property name="packagesToScan"
value="eu.cec.justice.common.domain.entity" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="javax.persistence.transactionType">jta</prop>
<prop key="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.WeblogicTransactionManagerLookup</prop>
<prop key="hibernate.current_session_context_class">org.hibernate.context.internal.JTASessionContext</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.my.common.util.ECLICommonEhCacheRegionFactory</prop>
<prop key="hibernate.ejb.cfgfile">hibernate.cfg.xml</prop>
</props>
</property>
</bean>
<bean id="dataSourceCommon" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="$${portal.common.database.jndi}" />
<property name="resourceRef" value="true" />
</bean>
<bean id="dataSourceEcli" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="$${ecli.database.jndi}" />
<property name="resourceRef" value="true" />
</bean>
<tx:jta-transaction-manager />
<tx:annotation-driven/>
EDIT:
Adding the following to the bean properties did not solve my issue (I also downgraded to Hibernate 5.0.0 but still the problem persists):
<prop key="hibernate.transaction.coordinator_class">org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl</prop>
This also didn't work:
<prop key="hibernate.transaction.coordinator_class">jta</prop>
This also deleting
<prop key="javax.persistence.transactionType">jta</prop>
but this failed as well.
As explained in the User Guide:
Hibernate tries to discover the JtaPlatform it should use through the
use of another service named
org.hibernate.engine.transaction.jta.platform.spi.JtaPlatformResolver.
If that resolution does not work, or if you wish to provide a custom
implementation you will need to specify the
hibernate.transaction.jta.platform setting.
Try providing the underlying JTA platform via the hibernate.transaction.jta.platform configuration property.
Three days of work to find out the solution. Added the following line to spring.xml:
<prop key="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.WeblogicJtaPlatform</prop>
Hibernate 4.x was somehow able to identify that automatically, but now you have to tell it manually which JtaPlatform you are using.

Spring / Hibernate application hangs during initialization

The web application deploys in other systems. but, it just hangs in my system.
Java Version: jdk1.8
TomcatVersion: apache-tomcat-7.0.63
Spring Version:4.1.6.RELEASE
Hibernate Version:4.3.5.Final
MySQL connector:5.0.8.bin jar
Please see the logs below.
Logs
[org.hibernate.dialect.Dialect] : [MySQL5] -> [org.hibernate.dialect.MySQL5Dialect] (replacing [org.hibernate.dialect.MySQL5Dialect])
[2014-01-14 13:44:25,537 main] [org.hibernate.boot.registry.selector.internal.StrategySelectorImpl : 79] [DEBUG] Registering named strategy selector [org.hibernate.dialect.Dialect] : [MySQL5InnoDB] -> [org.hibernate.dialect.MySQL5InnoDBDialect] (replacing [org.hibernate.dialect.MySQL5InnoDBDialect])
[2014-01-14 13:44:25,609 main] [org.hibernate.cfg.Configuration : 1841] [DEBUG] Preparing to build session factory with filters : {}
[2014-01-14 13:44:25,611 main] [org.hibernate.cfg.Configuration : 1841] [DEBUG] Preparing to build session factory with filters : {}
The deployment just hangs like a sleeping thread after this line. What might the problem? Please let me know if you need more information
EDIT 1 :
I have configured the hibernate sessionfactory via Spring dependency injection. Please check below
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mobile_recharge"/>
<property name="username" value="keerthi" />
<property name="password" value="keerthi" />
<property name="maxIdle" value="-1"></property>
<property name="maxActive" value="-1"></property>
<property name="maxOpenPreparedStatements" value="-1"></property>
<property name="maxWait" value="30000"></property>
<property name="validationQuery" value="SELECT 1"></property>
<property name="testOnBorrow" value="true"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.ciar.mobilerecharge.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="use_sql_comments">true</prop>
</props>
</property>
</bean>

Get Dialect within some class inside Spring MVC + Hibernate application

I have Hibernate Transaction manager configured inside Spring MVC controller.
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://127.0.0.1/doolloop2" />
<property name="username" value="doolloop2" />
<property name="password" value="doolloop" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingLocations">
<list>
<value>WEB-INF/mapping/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
In Addition, I have some class which needs to get Hibernate Dialect inside on of it method.
Is class is not Configured as bean inside Spring Framework.
How can I access Hibernate Dialect property from this class? I believe it should be some static class,but I don't know how can I do it. Please help.
You could separate the properties from the spring config. Put them in a properties file, then reference that in a PropertyPlaceholderConfigurer bean ( http://almaer.com/blog/spring-propertyplaceholderconfigurer-a-nice-clean-way-to-share ). Then you could inject that value into whatever bean it is that you need the value in the same way you are injecting it into the sessionFactory bean.

Spring and Hibernate inside Axis2 inside Tomcat6

I'm try to create web service base on axis2 (without a ServletContext). I have code that work properly (Spring + Hebirnate) and try to put it into AAR as it describe in this article and this one . All work good except hibernate.
I have:
<bean id="dataSourceCommon" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:oci:#xxxx" />
<property name="username" value="xxxx" />
<property name="password" value="xxxx" />
<property name="maxActive" value="10" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceCommon" />
<property name="mappingLocations">
<value>classpath:xxxx.hbm.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</prop>
</props>
</property>
</bean>
<bean id="hibernateDaoSupport" abstract="true"
class="org.springframework.orm.hibernate3.support.HibernateDaoSupport">
<property name="sessionFactory" ref="hibernateSessionFactory" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernateSessionFactory" />
</bean>
This file in root of AAR.
I copy this aar-file into c:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\axis2\WEB-INF\services, but if I try to run Tomcat server I get error:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name
'hibernateSessionFactory' defined in
class path resource
[xxxx.context.xml]: Instantiation of
bean failed; nested exception is
org.springframework.beans.BeanInstantiationException:
Could not instantiate bean class
[org.springframework.orm.hibernate3.LocalSessionFactoryBean]:
Constructor threw exception; nested
exception is
java.lang.NoClassDefFoundError
...
Caused by: java.lang.ClassNotFoundException:
org.hibernate.cfg.Configuration
where my mistake?
If the error is
java.lang.ClassNotFoundException: org.hibernate.cfg.Configuration
then the mistake is that you did not include the Hibernate classes (hibernate.jar, etc) on the claspath of your webapp (WEB-INF/lib).

Categories

Resources