load application context for junit hibernate tests inside spring - spring

I've got a properly defined spring configuration XML file, which imports some other XML files. THe test should read/write/delete records from MySQL database. I've got a problem with hibernate - the test is unable to access the database and hibernate throws following exception:
Unknown service requested [org.hibernate.stat.spi.StatisticsImplementor];
nested exception is org.hibernate.service.UnknownServiceException:
Unknown service requested [org.hibernate.stat.spi.StatisticsImplementor]
This is my test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(value = "classpath:*.xml")
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
#Transactional
public class JukeboxTest {
#Autowired
private ApplicationContext applicationContext;
private Jukebox jukebox;
private SessionFactory sessionFactory;
private Session session = null;
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
jukebox = (Jukebox) applicationContext.getBean("metal_jukebox");
sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
session = sessionFactory.openSession();
System.out.println(jukebox.getName());
}
#After
public void tearDown() {
session.close();
sessionFactory.close();
}
#Test
#Transactional
public void testGetName() {
assertEquals("Metal Jukebox", jukebox.getName());
}
This is my hibernate config 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: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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.blogspot.symfonyworld.lyricsbase.model.Song</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
the system.out line properly displays value defined in the bean XML, so the configuration is ok. I guess the annotations are somehow wrong, but I don't know what to fix, since the exception tells me nothing.
This is the exception stack trace:
org.springframework.orm.hibernate4.HibernateSystemException: Unknown service requested [org.hibernate.stat.spi.StatisticsImplementor]; nested exception is org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.stat.spi.StatisticsImplementor]
at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:185)
at org.springframework.orm.hibernate4.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:594)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:495)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:846)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:823)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.endTransaction(TransactionalTestExecutionListener.java:588)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.endTransaction(TransactionalTestExecutionListener.java:297)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:192)
at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:396)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:91)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.stat.spi.StatisticsImplementor]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:126)
at org.hibernate.internal.SessionFactoryImpl.getStatisticsImplementor(SessionFactoryImpl.java:1468)
at org.hibernate.internal.SessionFactoryImpl.getStatistics(SessionFactoryImpl.java:1464)
at org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl.afterTransaction(TransactionCoordinatorImpl.java:140)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.afterTransactionCompletion(JdbcTransaction.java:138)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.rollback(AbstractTransactionImpl.java:214)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:488)
... 33 more

Please define the bean JukeBox in the test context if this is a service.
If this is dao then please inject the entitymanager, transaction manager and session factory to the bean.

Related

how can we build a spring mvc multitenant application using hibernate as orm separate database and schema

from spring io u shifted to stack overflow but nowhere u have explained about multitenant complete demo application which can be seen as a problem solver infact no one seen satisfied with ur answers can u please now share a working demo of multitenant schema and separate database complete code anywhere where people can use it kindly
package com.domain.model;
import javax.persistence.*;
#Entity
#Table
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int employeeId;
#Column
private String employeeName;
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
}
package com.domain.multitenancy;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class CurrentTenantIdentifierResolverimpl implements CurrentTenantIdentifierResolver {
#Override
public String resolveCurrentTenantIdentifier() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String tenantId = attr.getRequest().getParameter("tenantId");
return tenantId;
}
#Override
public boolean validateExistingCurrentSessions() {
return true;
}
}
package com.domain.multitenancy;
import com.domain.master.MasterService;
import org.hibernate.service.jdbc.connections.spi.AbstractDataSourceBasedMultiTenantConnectionProviderImpl;
import javax.sql.DataSource;
public class MultiTenantConnectionprovideImpl extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl {
#Override
protected DataSource selectAnyDataSource() {
return MasterService.getDataSourceHashMap().get("tenantId1");
}
#Override
protected DataSource selectDataSource(String tenantIdentifier) {
return MasterService.getDataSourceHashMap().get(tenantIdentifier);
}
}
package com.domain.master;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import java.util.HashMap;
public class MasterService {
public static HashMap<String, DataSource> getDataSourceHashMap() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/multiten");
dataSource.setUsername("root");
dataSource.setPassword("root");
DriverManagerDataSource dataSource1 = new DriverManagerDataSource();
dataSource1.setDriverClassName("com.mysql.jdbc.Driver");
dataSource1.setUrl("jdbc:mysql://localhost:3306/multiten_1");
dataSource1.setUsername("root");
dataSource1.setPassword("root");
HashMap hashMap = new HashMap();
hashMap.put("tenantId1", dataSource);
hashMap.put("tenantId2", dataSource1);
return hashMap;
}
}
<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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.domain"/>
<mvc:annotation-driven/>
<context:property-placeholder location="classpath:application.properties"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
<property name="packagesToScan">
<list>
<value>com.domain.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
<prop key="hibernate.multiTenancy">DATABASE</prop>
<prop key="hibernate.tenant_identifier_resolver">com.domain.multitenancy.CurrentTenantIdentifierResolverimpl</prop>
<prop key="hibernate.multi_tenant_connection_provider">com.domain.multitenancy.MultiTenantConnectionprovideImpl</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
#Application.properties file in classpath
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/multiten
jdbc.username = root
jdbc.password = root
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql = true
hibernate.format_sql = false
I have taken this example
these are the errors i got:
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
org.hibernate.HibernateException: SessionFactory configured for
multi-tenancy, but no tenant identifier specified
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is
org.hibernate.HibernateException: SessionFactory configured for
multi-tenancy, but no tenant identifier specified
org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:544)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
com.sun.proxy.$Proxy22.save(Unknown Source)
com.domain.controller.EmployeeController.saveEmployee(EmployeeController.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
org.hibernate.HibernateException: SessionFactory configured for multi-tenancy, but no tenant identifier specified
org.hibernate.internal.AbstractSessionImpl.(AbstractSessionImpl.java:85)
org.hibernate.internal.SessionImpl.(SessionImpl.java:239)
org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1618)
org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:978)
org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:436)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
com.sun.proxy.$Proxy22.save(Unknown Source)
com.domain.controller.EmployeeController.saveEmployee(EmployeeController.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
Session for transaction; nested exception is
org.hibernate.HibernateException: SessionFactory configured for
multi-tenancy, but no tenant identifier specified
The above error suggests that tenant identifier is not specified. Please double check your configuration and the identifier class implementation name.
The reason you are getting this error is that your tenant identifier resolver needs to return something default in case it cannot find appropriate tenant id from the strategy you have chosen ( in your case you are trying to get the tenant id from request params). I have used the updated code below and it is no longer showing the error.
public class CurrentTenantIdentifierResolverimpl implements CurrentTenantIdentifierResolver {
#Override
public String resolveCurrentTenantIdentifier() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String tenantId = attr.getRequest().getParameter("tenantId");
if (tenantId==null) {
//return default tenant
return "tenantId1";
}
return tenantId;
}
#Override
public boolean validateExistingCurrentSessions() {
return true;
}
}
Shailendra sir how can we set a tenant id to it without setting default id and get the username from spring security and pass it to the tenant id

spring web mvc, webapplicationconfig currentsession integration

İ developed a web application using spring and hibernate. This is pretty huge app and i have to get some services from outside of controllers as well. For this i used xmlclasspathcontext to get beans at the same time.
Currently i am using threadlocal and opensession. So far i do not have problem except reading old data when update somethings. İ know this happens because of threadlocal keep current session.
What i want to learn is, İF i remove threadlocal and use öpensession and close session is it a good approach?
Because i cant use getcurrentsession with controllers and getbeans at the same time. İam getting no session found err at the xmXML get bean side. Is there a way to get getcurrentsession at both side? Or do i haveto use open and close session approach? What İF i do not close each opwnsession?
<?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:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.yupsoft.grid" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<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/grid" />
<property name="username" value="myuser" />
<property name="password" value="mypass" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.yupsoft.yupsoft.model.LanguageTextParameter</value>
<value>com.yupsoft.yupsoft.model.LoginHistory</value>
<value>com.yupsoft.yupsoft.model.Session</value>
<value>com.yupsoft.yupsoft.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!--
<prop key="hibernate.connection.autocommit">false</prop>
-->
<prop key="hibernate.connection.charSet">utf8</prop>
<prop key="hibernate.connection.characterEncoding">utf8</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.connection.autoReconnect">true</prop>
<prop key="current_session_context_class">thread</prop>
<prop key="hibernate.connection.pool_size">1</prop>
<prop key="hibernate.c3p0.min_size">10</prop>
<prop key="hibernate.c3p0.max_size">100</prop>
<prop key="hibernate.c3p0.timeout">1800</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="hibernate.c3p0.idle_test_period">30</prop>
<prop key="hibernate.c3p0.acquire_increment">1</prop>
<prop key="hibernate.c3p0.max_statements">0</prop>
<prop key="hibernate.c3p0.preferredTestQuery">select 1;</prop>
<prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>
<prop key="hibernate.connection.isolation">8</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
This is Controller class that I am getting requests
#Controller
public class UserController {
#Autowired
private UserService userService;
#Autowired
private LoginHistoryService loginHistoryService;
#RequestMapping(value = "/loginAttempt", method = RequestMethod.POST)
public #ResponseBody
String loginAttempt(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
String password = request.getParameter("password");
User user = userService.getByUserNameAndPassword(userName, password);
if (user != null) {
if (user.isActive()) {
LoginHistory loginHistory = new LoginHistory();
loginHistory.setCreated(new Date());
loginHistory.setIpAddress(request.getRemoteAddr());
loginHistory.setSessionId(request.getSession().getId());
loginHistory.setAccountVerified(Boolean.TRUE);
loginHistory.setUser(user);
boolean loginHistoryCreated = loginHistoryService.create(loginHistory);
if (loginHistoryCreated) {
return "ok";
} else {
//Error
return "err";
}
} else {
return "err";
}
}
return "ok";
}
}
This is Service layer
#Service("loginHistoryService")
#Transactional(propagation = Propagation.REQUIRED, readOnly = true, isolation = Isolation.SERIALIZABLE)
public class LoginHistoryServiceImpl extends GenericServiceImpl implements LoginHistoryService {
#Autowired
private LoginHistoryDAO loginHistoryDAO;
public LoginHistoryDAO getLoginHistoryDAO() {
return loginHistoryDAO;
}
public void setLoginHistoryDAO(LoginHistoryDAO loginHistoryDAO) {
this.loginHistoryDAO = loginHistoryDAO;
setGenericDAO(loginHistoryDAO);
}
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
#Override
public boolean create(LoginHistory obj) {
return loginHistoryDAO.create(obj);
}
This part is DAO layer
#Repository("loginHistoryDAO")
public class LoginHistoryDAOImpl extends GenericDAOImpl implements LoginHistoryDAO {
#Autowired
private SessionDAO sessionDAO;
#Override
public boolean create(LoginHistory obj) {
try {
//beginTransaction();
save(obj);
if (obj.isAccountVerified()) {
Session s = new Session();
s.setActive(Boolean.TRUE);
s.setIpAddress(obj.getIpAddress());
s.setCreated(new Date());
s.setSessionId(obj.getSessionId());
s.setUser(obj.getUser());
sessionDAO.save(s);
}
//commitTransaction();
} catch (Exception e) {
handleException(e);
return false;
}
return true;
}
}
And last part is generic part
#SuppressWarnings("unchecked")
#Repository
public abstract class GenericDAOImpl implements GenericDAO {
#Autowired
private SessionFactory sessionFactory;
private final Class<T> persistentClass;
public GenericDAOImpl() {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public Class<T> getPersistentClass() {
return persistentClass;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getCurrentSession() throws HibernateException {
return sessionFactory.getCurrentSession();
}
#Override
public Transaction beginTransaction() {
return getCurrentSession().beginTransaction();
}
#Override
public void commitTransaction() {
getCurrentSession().getTransaction().commit();
I am trying to replace openSession() to getCurrentSession()
and I require to control beginTransaction() and tx.commit(). Because I have more than one entity to save or update at the same time. So, I need to wrap those intities in a transaction, be sure all done or all did not done.
When I use getCurrentSession() I am getting this error;
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.virdyn.grid.core.system.filter.SessionFilter.doFilter(SessionFilter.java:88)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started
at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:660)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:412)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy166.create(Unknown Source)
at com.virdyn.grid.controller.UserController.loginAttempt(UserController.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
... 25 more
Caused by: org.hibernate.TransactionException: Transaction not successfully started
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:100)
at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:656)
... 43 more
I want to cancel ThreadLocal and use getCurrentSession.
What is wrong in here Or do you have other purposes. In fact I can use opensession() and closeSession for any method in all dao's. If I do that is it to slow my system?
I am waiting solutions thanks

Spring and Hibernate 4: get is not valid without active transaction

I am using Spring annotations and hibernate to create a DAO. I am using Spring 3.2.5 and hibernate 4.3.3. For some reason I keep getting this exception:
org.hibernate.HibernateException: get is not valid without active transaction
Here is the relevant portion of my spring app context:
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Pick up the HibernateHouseDAO spring bean -->
<context:component-scan base-package="jinvestor.jhouse.download" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>jinvestor.jhouse.core.HouseEntity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<!-- <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop> -->
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${dataSource.driver}" />
<property name="url" value="${dataSource.url}" />
<property name="username" value="${dataSource.username}" />
<property name="password" value="${dataSource.password}" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
This is my DAO:
#Repository("dao")
#Profile("mysql")
#Transactional
public class HibernateHouseDAO implements HouseDAO {
private final SessionFactory sessionFactory;
#Autowired
public HibernateHouseDAO(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public House load(long id) {
// this throws a nosuch method error for openSession.
// Session session = SessionFactoryUtils.getSession(sessionFactory, false);
// this throws an error on the lack of a transaction.
Session session = sessionFactory.getCurrentSession();
HouseEntity entity = (HouseEntity) session.get(HouseEntity.class, id);
return House.fromEntity(entity);
}
#Override
public void save(House house) {
sessionFactory.getCurrentSession().save(new HouseEntity(house));
}
BTW the #Transactional is spring's, not javax.transaction. Here is my unit test:
// MT stands for manual test
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath:/applicationContext.xml"})
#ActiveProfiles(profiles={"test","mysql"})
public class HibernateHouseDAOMT extends HouseDAOTest {
#Autowired
private HouseDAO dao;
#Override
public HouseDAO getDao() {
return dao;
}
}
Here is my SQL schema in case you need to know it:
create table homes (zpid BIGINT PRIMARY KEY NOT NULL, address VARCHAR(200) NOT NULL,squareFeet INT UNSIGNED,soldPrice INT UNSIGNED, latitude INT,longitude INT,lastSoldDate DATE, yearBuilt YEAR,acres FLOAT UNSIGNED,beds TINYINT UNSIGNED,baths TINYINT UNSIGNED, INDEX (address)) ENGINE = 'INNODB';
Also, all of my code is on github in case you want to see something I did not copy here. This is the project root on github:
https://github.com/msknapp/JInvestor/tree/master/JHouse/jhouse.download
Please help me get this to work.
===================
Update:
Switching to Hibernate Transaction Manager:
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
and here is the exception:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getConnectionProvider()Lorg/hibernate/service/jdbc/connections/spi/ConnectionProvider;
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 25 more
Caused by: java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getConnectionProvider()Lorg/hibernate/service/jdbc/connections/spi/ConnectionProvider;
at org.springframework.orm.hibernate4.SessionFactoryUtils.getDataSource(SessionFactoryUtils.java:90)
at org.springframework.orm.hibernate4.HibernateTransactionManager.afterPropertiesSet(HibernateTransactionManager.java:335)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
... 40 more
based on this, maybe I am missing a dependency in my pom, or have a bad dependency. I will try to find out...
I am using mysql-connector-java version 5.1.29, perhaps that is incompatible?
You're using Spring 3.2.5, and it's not compatible with the latest Hibernate 4.3.3 version that you're using. Hibernate 4.3 indeed decided to change the package of the ConnectionProvider returned by SessionFactoryImplementor.getConnectionProvider(). Use the latest Spring version, or use Hibernate 4.2, and it should run better.

Struts2; keeping a session open for StrutsSpringTestCase JUnit tests

My project architecture is Struts2 with Spring integration and JPA/Hibernate. StrutsSpringTestCase base class is utilized for JUnit integration tests.
Under normal circumstances, the following configuration in web.xml keeps a single session open from start to finish of each request:
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
As a result, all lazy loading works fine in all services. For example:
#Override
public Person find(int id) {
Person person = personDao.find(id);
// Take care of lazy loading before detaching the object for
// the view layer...
person.getGender().getCode();
// Detach the object so that it can be used for data transfer
// (as a DTO) without causing JPA issues and errors...
getEntityManager().detach(person);
return person;
}
Now... issues arise when I try to run the integration tests, which are independent of the OpenEntityManagerInViewFilter configuration in web.xml.
What happens is that since there is no session being kept open from start to finish of each request, lazy loading statements like "person.getGender().getCode()" don't work any longer, and I get the "could not initialize proxy - no Session" errors.
One solution I'm aware of is to force the #Transactional annotation upon the service methods that are having the lazy-loading issues, which will result in a session being open from start to finish of the method call. I tested it and it fixed the problem:
#Transactional
#Override
public Person find(int id) {
Person person = personDao.find(id);
// Take care of lazy loading before detaching the object for
// the view layer...
person.getGender().getCode();
// Detach the object so that it can be used for data transfer
// (as a DTO) without causing JPA issues and errors...
getEntityManager().detach(person);
return person;
}
However, this could be overkill as the method doesn't need a transaction under normal circumstances. I'm wondering if there is another solution that doesn't require to compromise on the service side.
Is there something I can add to my test classes (which extend StrutsSpringTestCase) to keep the session open? Or is there perhaps an elegant configuration solution on the Spring or JUnit side?
Here is my Spring configuration file - applicationContext.xml:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.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.0.xsd"
default-dependency-check="all"
default-lazy-init="false"
default-autowire="byName">
<!-- *************** MAIN CONFIGURATION SECTION *************** -->
<!-- Bean post-processor for JPA annotations. -->
<!-- Make the Spring container act as a JPA container and inject an EnitityManager from
the EntityManagerFactory. -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"
autowire="no"
dependency-check="none" />
<!-- ** Data Source Configuration ** -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
autowire="no"
dependency-check="none">
<!-- Database configuration: -->
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost/**********" />
<property name="user" value="**********" />
<property name="password" value="**********" />
<!-- C3P0 pooling properties configuration: -->
<property name="acquireIncrement" value="4" />
<property name="initialPoolSize" value="4" />
<property name="minPoolSize" value="4" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="600" />
<property name="maxConnectionAge" value="1800" />
</bean>
<!-- ** JPA Vendor Selection ** -->
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
autowire="no"
dependency-check="none" />
<!-- ** JPA Vendor and Entity Manager Configuration ** -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
autowire="no"
dependency-check="none">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<!-- Have the JPA vendor manage the database schema: -->
<prop key="hibernate.hbm2ddl.auto">create</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.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.max_fetch_depth">4</prop>
<prop key="hibernate.jdbc.batch_size">1000</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
</props>
</property>
</bean>
<!-- ** Transaction Manager Configuration ** -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
autowire="no"
dependency-check="none">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- ** Transaction Annotation Configuration; classes/functions with #Transactional will
get a framework transaction. ** -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- **** DETAILED SERVICE BEAN CONFIGURATION WAS TAKEN OUT TO SHORTEN THE FILE **** -->
</beans>
I would appreciate any pointers.
EDIT:
To make things a bit more visual, the following test generates an exception when the service method in question encounters lazy loading and the service method is not annotated with #Transactional, but works just fine when the service method is annotated with #Transactional.
public class ActionTest extends CustomActionTestBase {
public ActionTest() {
super("/web/someAction"); // the action to test
}
#Override
public void testHelperActionLoggedIn() throws Exception {
procApplyContinualSessionForAdmin(); // the numerous steps to get logged in
procExecuteAction(
helpGetPrimaryActionURI(), // use the action URI set by the constructor above
helpPrepareActionParams( ) // no parameters are passed to this action
);
procConfirmOutcome(ActionSupport.SUCCESS,0,0,0,false);
}
}
Note: CustomActionTestBase extends StrutsSpringTestCase (which in turn extends some JUnit stuff). I needed CustomActionTestBase due to some heavy test case customization/automation.
EDIT:
I also tried adding #Transactional to the "testHelperActionLoggedIn()" test method itself, which didn't change the outcome.
EDIT:
Additionally, I tried to make things more Spring-specific (as instructed by Aleksandr M) by annotating with #RunWith, #ContextConfiguration, and #Test.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class ActionTest extends CustomActionTestBase {
public ActionTest() {
super("/web/someAction"); // the action to test
}
#Test
#Override
public void testHelperActionLoggedIn() throws Exception {
procApplyContinualSessionForAdmin(); // the numerous steps to get logged in
procExecuteAction(
helpGetPrimaryActionURI(), // use the action URI set by the constructor above
helpPrepareActionParams( ) // no parameters are passed to this action
);
procConfirmOutcome(ActionSupport.SUCCESS,0,0,0,false);
}
}
It resulted in an exception that showed up in the JUnit Failure Trace - there was no exception output in the console for whatever reason.
Exception details:
java.lang.NullPointerException
at org.apache.struts2.StrutsTestCase.getActionMapping(StrutsTestCase.java:196)
at org.apache.struts2.StrutsTestCase.getActionMapping(StrutsTestCase.java:206)
at com.mycompany.utils.test.CustomActionTestBase.examineActionMapping(CustomActionTestBase.java:402)
at com.mycompany.utils.test.CustomActionTestBase.procExecuteAction(CustomActionTestBase.java:158)
at com.mycompany.utils.test.CustomActionTestBase.execLoginActionForAdmin(CustomActionTestBase.java:505)
at com.mycompany.utils.test.CustomActionTestBase.procApplyContinualSessionForAdmin(CustomActionTestBase.java:106)
at com.mycompany.actions.web.ActionTest.testHelperActionLoggedIn(ActionTest.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
It looks like it's having trouble with getting the action mapping, which it didn't before.
You can put #Transactional annotation over test method and you need to run your tests with spring in order it could find #Transactional annotation. To use JUnit4 in Struts2 tests you need to extend StrutsSpringJUnit4TestCase. So your test class should look something like that:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class ActionTest extends StrutsSpringJUnit4TestCase {
#Transactional
#Test
public void testHelperActionLoggedIn() throws Exception {
// ...
}
}
Note: If you need to obtain ActionProxy you can get it by calling getActionProxy method. You probably need to create new session map for it and then you can call execute.
ActionProxy actionProxy = getActionProxy("/action");
Map<String, Object> sessionMap = new HashMap<String, Object>();
actionProxy.getInvocation().getInvocationContext().setSession(sessionMap);
actionProxy.execute();
BUT if you don't need reference to ActionProxy then you can use executeAction method to execute action in this way you don't need to create new session map.
executeAction("/action");

Spring mvc test - testing controllers with Autowired annotations

I am trying to create some tests for my controllers using spring test framework.
Following this article: http://blog.springsource.org/2012/11/12/spring-framework-3-2-rc1-spring-mvc-test-framework/ I created this test class
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration("classpath:testContext.xml")
public class ServiceRequestControllerTest {
#Autowired
private WebApplicationContext wac;
#Autowired
private ServiceRequestController productController;
#Autowired
private WSServiceRequestIO wsServiceRequestIO;
#Autowired
private Open311ResponseMarshaller open311ResponseMarshaller;
#Autowired
private Open311GETQueryStringParser open311GETQueryStringParser;
#Autowired
private Open311POSTQueryStringParser open311POSTRequestParser;
#Autowired
private Open311ResponseFactory responseFactory;
private MockMvc mockMvc;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
#Test
public void testTest() throws Exception {
this.mockMvc.perform(get("/requests"));
}
}
and my testContext.xml is
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="utils.webservice.WSServiceRequestIO" />
</bean>
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="open311.model.Open311ResponseMarshaller" />
</bean>
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg
value="open311.utils.Open311POSTQueryStringParser" />
</bean>
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg
value="open311.utils.Open311GETQueryStringParser" />
</bean>
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg
value="open311.model.Open311ResponseFactory" />
</bean>
<context:component-scan base-package="open311.controller" />
<mvc:annotation-driven />
<mvc:resources mapping="/services*" location="/resources/" />
</beans>
now, when I run my tests I get a lot of messages like:
2013-04-19 14:33:34 INFO GenericTypeResolver:216 - Could not determine the target type for type argument [T] for method [public static <T> T org.mockito.Mockito.mock(java.lang.Class<T>)].
so there is some problem with inferring types by mockito, but still when I enter the debug mode and inspect my controller I can see that objects were injected correctly. (I am using #Autowire annotation in my controller).
Anyway, when I try to run this test I am getting test failure because of
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoSuchMethodError: javax/servlet/http/HttpServletResponse.getContentType()Ljava/lang/String;
at org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1259)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:816)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:168)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:136)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:134)
at open311.controller.ServiceRequestControllerTest.testTest(ServiceRequestControllerTest.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
what could be the source of my problem? I think that I followed every step from this tutorial.
The NoSuchMethodError indicates that you likely have an incompatible version of the Servlet API on your test classpath.
Also, you'll need to include your Spring MVC configuration as well as the bean definition for your ServiceRequestController within your test XML config, either directly, via an import, or by declaring a separate XML config file via #ContextConfiguration.

Resources