test and applicationContext - spring

i use latest release of spring, spring data, jpa, hibernate and h2.
i try to run test (only repository test).
but i get this error: Failed to load ApplicationContext
my test class
#RunWith(SpringJUnit4ClassRunner.class)
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
#Transactional
#ContextConfiguration(
locations = {"classpath:applicationContext-test.xml"})
public class UserDaoTest extends AbstractTransactionalJUnit4SpringContextTests {
...
}
my applicationContext-test.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:property-placeholder location="classpath:/jdbc.properties"/>
<context:component-scan base-package="com.test.*" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<jpa:repositories base-package="com.test.va.repository"/>
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="idleConnectionTestPeriodInMinutes" value="${jdbc.idleConnectionTestPeriodInMinutes}"/>
<property name="idleMaxAgeInSeconds" value="${jdbc.idleMaxAgeInSeconds}"/>
<property name="maxConnectionsPerPartition" value="${jdbc.maxConnectionsPerPartition}"/>
<property name="minConnectionsPerPartition" value="${jdbc.minConnectionsPerPartition}"/>
<property name="partitionCount" value="${jdbc.partitionCount}"/>
<property name="acquireIncrement" value="${jdbc.acquireIncrement}"/>
<property name="statementsCacheSize" value="${jdbc.statementsCacheSize}"/>
<property name="releaseHelperThreads" value="${jdbc.releaseHelperThreads}"/>
</bean>
so it's a config error.

Related

Spring jdbc transaction not commit

I have following Spring configuration:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" >
Beans with database and transaction management are configured as below:
<bean id="sufe.ncm.docDao" class="DocDaoImpl" scope="singleton">
<property name="jdbcTemplate" ref="sufe.ncm.jdbcTemplate"/>
</bean>
<bean id="sufe.ncm.jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="sufe.ncm.filterDB"/>
<property name="fetchSize" value="5000"/>
</bean>
<bean id="sufe.ncm.filterDB" class="org.apache.commons.dbcp.BasicDataSource">
<property name="defaultAutoCommit" value="false" />
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="..."/>
<property name="username" value="..."/>
<property name="password" value="..."/>
<property name="initialSize" value="1"/>
<property name="minIdle" value="1"/>
<property name="maxIdle" value="5"/>
<property name="maxOpenPreparedStatements" value="5"/>
</bean>
<context:annotation-config/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="sufe.ncm.filterDB"></property>
</bean>
DocDaoImpl class implements method updateData from interface DocDao:
#Transactional(rollbackFor = SQLException.class, propagation = Propagation.REQUIRES_NEW)
public synchronized void updateData() {
jdbcTemplate.batchUpdate(UPDATE_QUERY_1);
jdbcTemplate.batchUpdate(UPDATE_QUERY_1);
}
Because dataSource has set autocommit option on false, I expect that transaction will be committed only when both batchUpdates operation will finish whithout error. Unfortunatelly, unless both updates finishes whithout error, commit is not performed and I don't see any changes in database. Whats wrong ? Why #Transactional annotation doesn't work and commit is not performed ?

SessionFactory is null

I'm using Spring with Hibernate and originally set up my project with a hibernate xml config, which resulted in performance issues and seemed like it was the wrong way to do it. I'm now trying to inject my SessionFactory, starting with 1 dao, but get a null pointer exception where sessionFactory.getCurrentSession() is called. I think my code looks like the examples I've seen. I'm stumped. I also tried not using resource and injecting the sessionFactory into the dao in the application context instead. Same result.
ApplicationContext.xml
<context:component-scan base-package="path.to.base">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingDirectoryLocations">
<list>
<value>classpath*:/path/to/mapping/files</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
myDAO
#Repository
public class myDAO {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory(){
return sessionFactory;
}
#Resource(name="sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public myDAO() {
}
#SuppressWarnings("unchecked")
#Transactional(readOnly=true)
public List<Things> getAllThings() {
return sessionFactory.getCurrentSession().createCriteria(EvalMasterEvaluationType.class)
.add(Restrictions.eq("active", "Y")).addOrder(Order.desc("createDtTm")).list();
}
}
Spring 3.2.1, Hibernate 3.6.10
I got it working, though I'm not sure which modification solved the problem. SRT_KP might be right after all about the datasource since I added some properties to it (maxactive, maxidle, validationquery). I switched to LocalSessionFactoryBean since I'm using xml mappings and added the mapping file suffix to the mappingLocations property. I also moved #Transactional to the service layer where it belongs.
Here's what I ended up with:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:property-placeholder location="classpath*:WEB-INF/*.properties"/>
<context:component-scan base-package="org.base.to.scan">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="oraDataSource" />
<property name="mappingLocations" value="classpath*:org/path/to/mapping/files/*.hbm.xml" />
</bean>
<bean id="oraDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
<property name="validationQuery" value="SELECT 'x' FROM dual" />
</bean>
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
BTW great tutorial: http://www.byteslounge.com/tutorials/spring-with-hibernate-persistence-and-transactions-example

Spring-JPA-Hibernate Configuration: setting property hiberate.hbm2dll.auto to create has no effect?

I have this configuration problem:
1) I have jpaPropertyMap with property hibernate.hbm2dll.auto set to create but it has no effect. Its not creating table generation SQL.
I can see in log file other jpaPropertyMap property like dialect getting properly set so property map is being read.
2) If i set HibernateJpaVendorAdapter's property generateddl to true, table is being generated.
so why does hibernate.hbm2dll.auto not working in the case/generating tables.
Here is the Configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="org.demoapps.placementwebsite"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/cpm?autoReconnect=true" />
<property name="username" value="user" />
<property name="password" value="password" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<entry key="hibernate.hbm2dll.auto" value="create"/>
<entry key="hibernate.format_sql" value="true" />
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
Using:
Hibernate 4.2.2.Final
Spring 3.2.3.RELEASE
The property is hibernate.hbm2ddl.auto, and not hibernate.hbm2dll.auto.
DDL = Data Definition Language
DLL = Dynamic-Link Library

java.lang.ClassCastException: org.apache.xerces.parsers.SAXParser cannot be cast to org.xml.sax.XMLReader Hibernate

I am working on a project with Hibernate JPA /spring.
It throws the following exception. After doing some reading I removed all the xml-apis from dependencies but it throws the same error. Any ideas ??
java.lang.ClassCastException: org.apache.xerces.parsers.SAXParser cannot be cast to org.xml.sax.XMLReader
at org.xml.sax.helpers.XMLReaderFactory.loadClass(XMLReaderFactory.java:199)
at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(XMLReaderFactory.java:150)
at org.dom4j.io.SAXHelper.createXMLReader(SAXHelper.java:83)
at org.dom4j.io.SAXReader.createXMLReader(SAXReader.java:894)
at org.dom4j.io.SAXReader.getXMLReader(SAXReader.java:715)
at org.dom4j.io.SAXReader.setFeature(SAXReader.java:218)
at org.hibernate.internal.util.xml.MappingReader.setValidationFor(MappingReader.java:114)
at org.hibernate.internal.util.xml.MappingReader.readMappingDocument(MappingReader.java:77)
at org.hibernate.cfg.Configuration.add(Configuration.java:478)
at org.hibernate.cfg.Configuration.add(Configuration.java:474)
at org.hibernate.cfg.Configuration.add(Configuration.java:647)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:685)
at org.hibernate.ejb.Ejb3Configuration.addClassesToSessionFactory(Ejb3Configuration.java:1248)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:1048)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:693)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:73)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
while I am trying to initialise the web context in jetty web server it throw the above exception.[Spring (3.0.6.Release) & hibernate (4.1.10.final) ]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<import resource="classpath*:/META-INF/spring-orchestra-init.xml"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:persistenceUnitName="persistenceUnit">
<property name="dataSource" ref="dataSource"/>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="false"/>
</bean>
</property>
<property name="loadTimeWeaver">
<bean class="org.faces.controller.jpa.JpaLoadTimeWeaver"/>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="conversation.access">
<bean class="org.apache.myfaces.orchestra.conversation.spring.SpringConversationScope">
<property name="advices">
<list>
<ref bean="persistentContextConversationInterceptor" />
</list>
</property>
</bean>
</entry>
</map>
</property>
</bean>
<bean id="jpaPersistentContextFactory" class="org.apache.myfaces.orchestra.conversation.spring.JpaPersistenceContextFactory">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="persistentContextConversationInterceptor" class="org.apache.myfaces.orchestra.conversation.spring.PersistenceContextConversationInterceptor">
<property name="persistenceContextFactory" ref="jpaPersistentContextFactory" />
</bean>
<bean name="org.apache.myfaces.orchestra.conversation.AccessScopeManagerConfiguration"
class="org.apache.myfaces.orchestra.conversation.AccessScopeManagerConfiguration"
scope="singleton" lazy-init="true">
<property name="ignoreViewIds">
<set>
<value>/__ADFv__.xhtml</value>
</set>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#rum:1541:CHEZTST" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
After removing the loadtimeweaver property it worked fine.
<property name="loadTimeWeaver">
<bean class="org.faces.controller.jpa.JpaLoadTimeWeaver"/>
</property>
this is the link that shows that, although it is quite old it works
https://jira.springsource.org/browse/SPR-2596

Inject common attribute from spring configuration file to every test class

I have small clarification regarding the spring injection. I'm writing the test for services. Every Test class has a common attribute called "tenantId". Can I inject that attribute through spring configuration file.I don't want to add every test class to the spring configuration file, Is there a way to that?
#ContextConfiguration(locations = {"classpath*:applicationContext-service-test.xml"})
public class ApplicationServiceTest extends AbstractTestNGSpringContextTests {
#Autowired
TenantBasedSessionFactory tenantBasedSessionFactory;
#Autowired
private ApplicationService applicationService;
private String tenantId = "tenantId"; // I want this to inject from applicationContext-service-test.xml
private Session session;
}
Spring configuration file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Use #Transaction annotations for managing transactions -->
<tx:annotation-driven/>
<!-- Activates scanning of #Autowired -->
<context:annotation-config/>
<!-- Activates scanning of #Service and #Repository -->
<context:component-scan base-package="lk.gov.elg"/>
<!-- JDBC property file -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<!--<value>classpath:test.jdbc.properties</value>-->
<value>jdbc.properties</value>
</list>
</property>
</bean>
<!--<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"-->
<!--p:driverClassName="org.hsqldb.jdbcDriver" p:url="jdbc:hsqldb:mem:test"-->
<!--p:username="sa" p:password="" />-->
<!-- create database connection pool -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<!--<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">-->
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="100"/>
<property name="maxWait" value="1000"/>
<property name="poolPreparedStatements" value="true"/>
<property name="defaultAutoCommit" value="true"/>
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="lk.gov.elg.orm.model"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=${hibernate.dialect.test}
hibernate.hbm2ddl.auto=update
hibernate.cache.use_second_level_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="tenantBasedSessionFactory" class="lk.gov.elg.orm.dao.impl.TenantBasedSessionFactoryImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
Thank you in advance
Cheers
You can create a common superclass for all your tests to inject there your tenantId. With this, you will only have to inject only once and tenandId will be available to all your desired classes.

Resources