Spring - Hibernate Connection error - maven

When I try to test DAO class with JUnit,it throws following error
org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl#1255b1d1 is closed
I am using Spring 4 with Hibernate 5, mysql and maven
java.lang.IllegalStateException: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl#1255b1d1 is closed
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.errorIfClosed(AbstractLogicalConnectionImplementor.java:37)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:128)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:247)
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.rollback(AbstractLogicalConnectionImplementor.java:114)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.rollback(JdbcResourceLocalTransactionCoordinatorImpl.java:239)
at org.hibernate.engine.transaction.internal.TransactionImpl.rollback(TransactionImpl.java:100)
at org.springframework.orm.hibernate5.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:608)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.doRollbackOnCommitException(AbstractPlatformTransactionManager.java:900)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:789)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy20.saveUser(Unknown Source)
at TestUserDao.testSaveUser(TestUserDao.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
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:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Hibernate-test.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:property-placeholder location="classpath:database.properties" />
<context:component-scan base-package="com.timelee" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> -->
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>com.timelee.timesheet.models</value>
<value>com.timelee.users.models</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<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>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
TestUserDao.java
import com.timelee.users.dao.UserDao;
import com.timelee.users.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/Hibernate-test.xml")
public class TestUserDao
{
#Autowired
private UserDao userDao;
#Test
public void testSaveUser()
{
User user=new User();
user.setFirstName("Pavan");
boolean result=userDao.saveUser(user);
}
}
UserDaoImpl.java
package com.timelee.users.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.timelee.users.model.User;
#Repository("userDao")
#Transactional
public class UserDaoImpl extends AbstractDao implements UserDao
{
#Autowired
private SessionFactory sessionFactory;
public boolean saveUser(User user)
{
Transaction tx = null;
Session session=sessionFactory.getCurrentSession();
try
{
tx = session.beginTransaction();
session.saveOrUpdate(user);
tx.commit();
return true;
}
catch (Exception e)
{
if (tx!=null)
tx.rollback();
e.printStackTrace();
return false;
}
finally
{
session.close();
}
}
#SuppressWarnings("unchecked")
public List<User> getUsers()
{
List<User> users;
Transaction tx = null;
Session session=sessionFactory.getCurrentSession();
try
{
tx = session.beginTransaction();
users=(List<User>) session.createQuery("FROM USER");
tx.commit();
return users;
}
catch (Exception e)
{
if (tx!=null)
tx.rollback();
e.printStackTrace();
}
finally {
session.close();
}
return null;
}
public User getUser(String id)
{
User user;
Transaction tx = null;
Session session=sessionFactory.getCurrentSession();
try
{
tx = session.beginTransaction();
user=(User)session.get(User.class,id);
tx.commit();
return user;
}
catch (Exception e)
{
if (tx!=null)
tx.rollback();
e.printStackTrace();
return null;
}
finally
{
session.close();
}
}
public boolean updateUser(User user)
{
Transaction tx = null;
Session session = sessionFactory.getCurrentSession();
try
{
tx = session.beginTransaction();
session.update(user);
tx.commit();
return true;
}
catch (Exception e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
return false;
}
finally
{
session.close();
}
}
public boolean deleteUserById(String id)
{
User user = new User();
user.setId(id);
Transaction tx = null;
Session session = sessionFactory.getCurrentSession();
try
{
tx = session.beginTransaction();
session.delete(user);
tx.commit();
return true;
}
catch (Exception e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
return false;
}
finally
{
session.close();
}
}
}

at org.springframework.transaction.support.AbstractPlatformTransactionManager.doRollbackOnCommitException(AbstractPlatformTransactionManager.java:900)
Spring Test is trying to automate the transactions for you in testing, so you definitely don't need to manage any of the JPA / transaction stuff yourself.
If you do want to manage the transactions, then don't mark it as #Transactional.
You might benefit from spring-data-jpa as well. It will let you scrap most of your DAOs.

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

Exception in thread "main" java.lang.ExceptionInInitializerError

Currently I am new to spring to trying to implement data-source with MySQL but I am facing a error but not able to understand what is main reason or error.
Exception in thread "main" java.lang.ExceptionInInitializerError
Apr 26, 2015 8:09:33 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#4ee70b: startup date [Sun Apr 26 20:09:33 IST 2015]; root of context hierarchy
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.springframework.context.support.AbstractRefreshableApplicationContext.createBeanFactory(AbstractRefreshableApplicationContext.java:194)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:127)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:465)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:395)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.rajdeo.jdbcspring.JdbcDemo.main(JdbcDemo.java:12)
Caused by: java.lang.NullPointerException
at org.springframework.beans.factory.support.DefaultListableBeanFactory.<clinit>(DefaultListableBeanFactory.java:104)
... 7 more
JdbcDemo.java
package com.x.jdbcspring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.x.jdbcspring.JdbcDaoImpl;
public class JdbcDemo {
public static void main(String[] args) {
ApplicationContext ctx= new ClassPathXmlApplicationContext("spring.xml");
JdbcDaoImpl dao=ctx.getBean("JdbcDaoImpl",JdbcDaoImpl.class);
/*
//JdbcDaoImpl dao=new JdbcDaoImpl();
Student student=ctx.getStudent(1);
System.out.println("name::\t"+student.getName());
JdbcDaoImpl jdbc=new JdbcDaoImpl();
jdbc.getStudent(1);
System.out.println(jdbc.getStudent(1).getId());*/
}
}
JdbcDaoImpl.java
package com.x.jdbcspring;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class JdbcDaoImpl {
#Autowired
private DataSource datasource;
public DataSource getDatasource() {
return datasource;
}
public void setDatasource(DataSource datasource) {
this.datasource = datasource;
}
public Student getStudent(int id){
Connection con = null;
Student student=null;
try{
/* Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");*/
con = datasource.getConnection();
PreparedStatement stmt=con.prepareStatement("select * from contact where contact_id =?");
stmt.setInt(1, id);
//Excute the query
ResultSet rs=stmt.executeQuery();
while(rs.next()){
String name=rs.getString("name");
student=new Student(id, name);
}
//close the statement and Resultset
stmt.close();
rs.close();
return student;
}catch(Exception e){
e.printStackTrace();
}
finally{
if(con!=null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return student;
}
}
Student.java
package com.rajdeo.jdbcspring;
public class Student {
private int id;
private String name;
public Student(int id, String name) {
// TODO Auto-generated constructor stub
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
spring.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config />
<context:component-scan base-package="com.rajdeo" />
<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/student" />
<property name="username" value="root" />
<property name="password" value="xxxx" />
</bean>
</beans>
What is error I am not able to understand it any help is appreciated.
Your spring.xml says to scan the package com.rajdeo for components, but your class JdbcDaoImpl is in package com.x.jdbcspring and so it will not be picked up, even though it has a #Component annotation.
Make sure to include the package that contains JdbcDaoImpl in the component scanning process:
<context:component-scan base-package="com.rajdeo, com.x.jdbcspring" />
Looks like you are getting a bean from the context
ctx.getBean("JdbcDaoImpl",JdbcDaoImpl.class)
but in the spring.xml this bean is not defined. As a result you get NPE = java.lang.NullPointerException.
To resolve this issue you have to configure JdbcDaoImpl service. E.g.
<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/student" />
<property name="username" value="root" />
<property name="password" value="xxxx" />
</bean>
<bean id="JdbcDaoImpl"
class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<property name="datasource" ref="datasource"/>
</bean>

sessionFactory is null when accessing DAO

I am trying to integrate Spring+Hibernate4, but when I access my DAOs I get a nullPointerException on the sessionFactory object.
This is my AbstractDao:
#Repository
public class AbstractDaoHibernateImpl {
private SessionFactory sessionFactory;
public AbstractDaoHibernateImpl() {
}
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
protected Session getSession() {
return getSessionFactory().getCurrentSession();
}
protected Order getOrder(String orderBy, boolean isOrderAsc) {
if (isOrderAsc)
return Order.asc(orderBy);
else
return Order.desc(orderBy);
}
}
This is my entity bean config:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- transacciones -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
<!--Beans de los servicios de la aplicacion -->
<bean id="userService" class="com.app.service.user.UserServiceImpl"/>
<bean name="userDAO" class="com.app.model.user.dao.UserDaoImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
And this is the rest of my appContext
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-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
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<context:component-scan base-package="com.app.controllers" />
<mvc:annotation-driven />
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager"/>
<import resource="applicationDatasource.xml" />
<import resource="applicationEntityBean.xml" />
</beans>
And finally this is my Service object:
#Service
public class UsuarioServiceImpl implements IUsuarioService {
#Autowired
private IUserDao userDao;
public List<User> getUsers() throws GenericDataBaseException {
return userDao.findAll();
}
}
Shouldn't the sessionFactory object be injected like this?
This is the whole stack trace:
java.lang.NullPointerException
at es.plexus.core.dao.impl.GenericDaoHibernateImpl.findAll(GenericDaoHibernateImpl.java:243)
at es.plexus.service.usuario.UsuarioServiceImpl.getUsuarios(UsuarioServiceImpl.java:20)
at es.plexus.controller.usuario.UsuarioController.listUsuarios(UsuarioController.java:24)
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:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:722)
EDIT: userDao:
public class UserDaoImpl extends GenericDaoHibernateImpl<Usuario, Long> implements IUserDao {
}
which extends GenericDao:
public class GenericDaoHibernateImpl<E, PK extends Serializable> extends AbstractDaoHibernateImpl implements GenericDao<E, PK> {
private Class<E> entityClass;
public GenericDaoHibernateImpl() {
this.entityClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public List<E> findAll() throws GenericDataBaseException {
try {
Criteria criteria = getSession().createCriteria(getEntityClass());
List<E> result = criteria.list();
/*
* if (result == null || result.size() == 0) throw new
* NoSearchResultException("", getEntityClass().getName());
*/
return result;
} catch (Throwable t) {
Collection<Object> args = new ArrayList<Object>();
throw exceptionHandler.handle(this, t, "findAll", args);
}
}
(...)
}
I see no transactions defined anywhere in your code.
In this case I recommend you put them on your service method :
#Transactional(readOnly = true)
public List<User> getUsers() throws GenericDataBaseException {
return userDao.findAll();
}
But you seem to be developing a rather complex class hierarchy, all you need is one generic repository and then instantiate that for different types. You don't have to use a service class, they are only recommended when using multiple aggregate roots/complex logic - not a simple getter.
Let me take a guess.
Is your DAO under the package com.app.controllers? If not add your dao package to the component scan as in <context:component-scan base-package="com.app.controllers, com.app.model.user.dao" />

Spring AOP Declarative Transaction Management Not Working

I'm trying to write a simple application to learn how Transaction works in Spring (Declarative AOP Style). I'm inserting one record into customer table and then throwing NullPointerException to see if the inserted data is rolled back or not. But to my surprise it's not rolling back the data. Here is the code
ApplicationContext.xml file
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
">
<aop:aspectj-autoproxy />
<bean id="BoardingService" class="com.learning.maven.services.BoardingServiceImpl"/>
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<tx:method name="getUser*" rollback-for="throwable" propagation="REQUIRES_NEW"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="boardingServiceOperation" expression="execution(* com.learning.maven.services.BoardingService.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="boardingServiceOperation"/>
</aop:config>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</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:#localhost:1521:XE"/>
<property name="username" value="system"/>
<property name="password" value="Manager"/>
</bean>
<bean id="customerDAO" class="com.learning.maven.dao.CustomerDAOImpl">
<property name="dataSource" ref="dataSource" />
</bean>
This is how I call method
public static void main(String[] args) {
context = new FileSystemXmlApplicationContext("C:\\workspace\\learning\\cxf\\SpringTransaction\\cxf.xml");
BoardingService bean = (BoardingService) context.getBean("BoardingService");
bean.getUser("1");
}
And the BoardingService Class Looks like below
public class BoardingServiceImpl implements BoardingService, ApplicationContextAware {
ApplicationContext context = null;
public String getUser(String id) {
String response = "SUCCESS";
try{
System.out.println("Testing");
CustomerDAO customerDAO = (CustomerDAO) Testing.context.getBean("customerDAO");
Customer c = new Customer();
c.setAge(31);
c.setCustId(1);
c.setName("Jagadeesh");
customerDAO.insert(c);
customerDAO.insert(null);
}
catch(Exception e){
throw new RuntimeException();
}
return response;
}
#Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
this.context = arg0;
}
and the CustomerDAOImpl
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void insert(Customer customer) {
String sql = "INSERT INTO CUSTOMER (CUST_ID, NAME, AGE) VALUES (?, ?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, customer.getCustId());
ps.setString(2, customer.getName());
ps.setInt(3, customer.getAge());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
public Customer findByCustomerId(int custId) {
// TODO Auto-generated method stub
return null;
}
Not sure where am I going wrong. Any Pointers will be of great help.
You have rollback-for "throwable" instead of "Throwable".
P.S. Not sure that you should use REQUIRES_NEW as the default strategy.
update: From DataSourceTransactionManager documentation
Application code is required to retrieve the JDBC Connection via
DataSourceUtils.getConnection(DataSource) instead of a standard
J2EE-style DataSource.getConnection() call. Spring classes such as
JdbcTemplate use this strategy implicitly. If not used in combination
with this transaction manager, the DataSourceUtils lookup strategy
behaves exactly like the native DataSource lookup; it can thus be used
in a portable fashion.
In your case you open connection directly and then Oracle commits transaction on close(this is a feature of Oracle RDBMS).
You can also just omit the rollback-for attribute. Then it will rollback if any RuntimeException occurs.

Spring + Eclipselink + JtaTransactionManager = javax.persistence.TransactionRequiredException

I really hope you can help me. I've been looking all over the internet for answers and none of them works.
I use Spring 3 + JTA + EclipseLink but i'm getting a TransactionRequiredException when flushing a transaction. Now i'm very used to just defining my persistence context and injecting the EntityManager and the transaction is handled by the app server.
So here's what I've got.
persistence.xml
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="CartouchanPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>java:app/jdbc/CartouchanDS</jta-data-source>
<class>com.cartouchan.locator.database.models.Authority</class>
<class>com.cartouchan.locator.database.models.AuthorityPK</class>
<class>com.cartouchan.locator.database.models.User</class>
<class>com.cartouchan.locator.database.models.UserPK</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.ddl-generation" value="none"/>
<property name="eclipselink.target-database" value="MySQL"/>
<property name="eclipselink.jdbc.native-sql" value="true"/>
<property name="eclipselink.jdbc.cache-statements" value="true"/>
</properties>
</persistence-unit>
</persistence>
spring-config.xml
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<jee:jndi-lookup jndi-name="java:app/jdbc/CartouchanDS" id="CartouchanDS" />
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="autodetectUserTransaction" value="true" />
<property name="autodetectTransactionManager" value="true" />
<property name="transactionManagerName" value="java:appserver/TransactionManager"/>
</bean>
<context:annotation-config />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="CartouchanPU" />
<property name="persistenceUnitManager">
<bean class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"/>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
</property>
</bean>
CreateAccount.class
import java.text.MessageFormat;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class CreateAccount implements Controller {
private static final Logger logger = Logger.getLogger(CreateAccount.class);
// #Autowired
// private JtaTransactionManager transactionManager;
#PersistenceContext
private EntityManager entityManager;
#Transactional(propagation = Propagation.REQUIRES_NEW)
#Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info(MessageFormat.format("Called handle request", ""));
String username = ServletRequestUtils.getRequiredStringParameter(request, "username");
logger.info(MessageFormat.format("username {0}", username));
String password = ServletRequestUtils.getRequiredStringParameter(request, "password");
logger.info(MessageFormat.format("password {0}", password));
String passwordConfirm = ServletRequestUtils.getRequiredStringParameter(request, "passwordConfirm");
logger.info(MessageFormat.format("passwordConfirm {0}", passwordConfirm));
if (!password.equals(passwordConfirm)) {
throw new ServletRequestBindingException("Passwords don't match");
}
//transactionManager.getUserTransaction().begin();
User user = new User();
//try {
UserPK userPK = new UserPK();
userPK.setUsername(username);
user.setId(userPK);
user.setPassword(passwordConfirm);
user.setEnabled((byte) 1);
logger.info(MessageFormat.format("persist the user {0}", username));
entityManager.persist(user);
entityManager.flush();
// logger.info(MessageFormat.format("Before Refresh user {0}", username));
// entityManager.refresh(user);
// transactionManager.getUserTransaction().commit();
// } catch (Exception e) {
// logger.error(MessageFormat.format("Got an exception {0}", e.getMessage()), e);
// transactionManager.getUserTransaction().rollback();
// }
// transactionManager.getUserTransaction().begin();
// AuthorityPK authorityPK = new AuthorityPK();
// //try {
// logger.info(MessageFormat.format("Refreshed user {0} = {1}", username, user.getId()));
//
// authorityPK.setUserId(user.getId().getId());
// authorityPK.setAuthority(com.cartouchan.locator.models.Authority.ROLE_USER.toString());
// Authority authority = new Authority();
// authority.setId(authorityPK);
//
// logger.info(MessageFormat.format("Save the authority {0}", com.cartouchan.locator.models.Authority.ROLE_USER.toString()));
// entityManager.persist(authority);
// transactionManager.getUserTransaction().commit();
// } catch (Exception e) {
// logger.error(MessageFormat.format("Got an exception {0}", e.getMessage()), e);
// transactionManager.getUserTransaction().rollback();
// }
logger.info(MessageFormat.format("Go to /index.zul", ""));
ModelAndView modelAndView = new ModelAndView("index");
logger.info(MessageFormat.format("Return ", ""));
return modelAndView;
}
}
So here's the deal, when I uncomment the transactionManager parts, the program operates as expected, which is I can see the insert statements. However, when using the above code, I get the following stacktrace :
INFO: Starting ZK 5.0.7.1 CE (build: 2011051910)
INFO: Parsing jndi:/server/Cartouchan/WEB-INF/zk.xml
INFO: WEB0671: Loading application [Cartouchan-Web] at [/Cartouchan]
INFO: Cartouchan-Web was successfully deployed in 1,537 milliseconds.
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] Called handle request
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] username blah
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] password test
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] passwordConfirm test
INFO: 2011-08-04 01:09:52 CreateAccount [INFO] persist the user blah
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: EclipseLink, version: Eclipse Persistence Services - 2.2.0.v20110202-r8913
CONFIG: connecting(DatabaseLogin(
platform=>MySQLPlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
CONFIG: Connected: jdbc:mysql://localhost:3306/Cartouchan
User: root#localhost
Database: MySQL Version: 5.1.51
Driver: MySQL-AB JDBC Driver Version: mysql-connector-java-5.1.11 ( Revision: ${svn.Revision} )
CONFIG: connecting(DatabaseLogin(
platform=>MySQLPlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
CONFIG: Connected: jdbc:mysql://localhost:3306/Cartouchan
User: root#localhost
Database: MySQL Version: 5.1.51
Driver: MySQL-AB JDBC Driver Version: mysql-connector-java-5.1.11 ( Revision: ${svn.Revision} )
INFO: file:/Applications/NetBeans/glassfish-3.1/glassfish/domains/domain1/eclipseApps/Cartouchan-Web/WEB-INF/classes/_CartouchanPU login successful
WARNING: StandardWrapperValve[cartouchan]: PWC1406: Servlet.service() for servlet cartouchan threw exception
javax.persistence.TransactionRequiredException:
Exception Description: No externally managed transaction is currently active for this thread
at org.eclipse.persistence.internal.jpa.transaction.JTATransactionWrapper.throwCheckTransactionFailedException(JTATransactionWrapper.java:86)
at org.eclipse.persistence.internal.jpa.transaction.JTATransactionWrapper.checkForTransaction(JTATransactionWrapper.java:46)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.checkForTransaction(EntityManagerImpl.java:1666)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:744)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365)
at $Proxy151.flush(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at $Proxy151.flush(Unknown Source)
at com.cartouchan.locator.controllers.CreateAccount.handleRequest(CreateAccount.java:56)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:112)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:170)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:680)
So as you can see, it connects correctly to the database, and it "persists" the data, but never actually execute the insert statement. Then when flushing the EM, it throws the exception.
Your help will be greatly appreciated.
Best Regards.
Ok, so I figured out how to get this working 100%.
First of all, I don't have to define any persistence(context/unit) in web.xml. Next I removed the transactionmanager and the entityManagerFactory beans. Also removed the context:driven line.
I also made my "beans" Stateless session beans. I then instantiate it through spring through jndi context lookups. This autowires the entitymanager exactly as i want it. No more worrying about transactions, the app server handles that.
so my final config is :
spring-config.xml :
<jee:jndi-lookup jndi-name="java:global/Cartouchan-Web/CategoryController" id="categoryController"/>
<jee:jndi-lookup jndi-name="java:global/Cartouchan-Web/UserController" id="userController"/>
<bean id="applicationContextProvider" class="com.cartouchan.locator.beans.CustomApplicationContext"></bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
bean sample:
import java.text.MessageFormat;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.log4j.Logger;
#Stateless
public class CategoryController {
private static final Logger logger = Logger.getLogger(CategoryController.class);
#PersistenceContext
private EntityManager entityManager;
public CategoryController() {
// TODO Auto-generated constructor stub
}
public boolean createCategory(final String name) {
boolean result = false;
try {
com.cartouchan.locator.database.models.Category category = new com.cartouchan.locator.database.models.Category();
category.setName(name);
entityManager.persist(category);
entityManager.flush();
result = true;
} catch (Exception ex) {
logger.error(MessageFormat.format("Could not create the category {0}", name), ex);
}
return result;
}
public boolean updateCategory(final int id, final String name) {
boolean result = false;
try {
com.cartouchan.locator.database.models.Category category = getCategory(id);
category.setName(name);
entityManager.merge(category);
entityManager.flush();
result = true;
} catch (Exception ex) {
logger.error(MessageFormat.format("Could not update for the category {0} -{1}", id, name), ex);
}
return result;
}
public boolean deleteCategory(final int id) {
boolean result = false;
try {
com.cartouchan.locator.database.models.Category category = getCategory(id);
entityManager.remove(entityManager.merge(category));
entityManager.flush();
result = true;
} catch (Exception ex) {
logger.error(MessageFormat.format("Could not delete for the category {0}", id), ex);
}
return result;
}
public com.cartouchan.locator.database.models.Category getCategory(final int id) {
return (com.cartouchan.locator.database.models.Category) entityManager.createQuery("select p from Category p where p.id=:id").setParameter("id", id).getSingleResult();
}
public List<com.cartouchan.locator.database.models.Category> getAllCategories() {
return (List<com.cartouchan.locator.database.models.Category>) entityManager.createQuery("select p from Category p").getResultList();
}
}
Then to use the bean, just do a standard spring lookup of the bean. Easy as pie.
In order to use JTA transactions managed by the application server you need to use EntityManagerFactroy created by the application server itself.
I.e. you need to remove your LocalContainerEntityManagerFactoryBean declaration and obtain EntityManagerFactory from the application server via <jee:jndi-lookup>. Also you should configure application server to create EntityManagerFactory - see your application server documentation.
See also:
13.5.1.2 Obtaining an EntityManagerFactory from JNDI
property name="eclipselink.target-server" value="WebSphere_7"
set the server type....
hope this one should work..
refer the docs for more details
http://docs.oracle.com/middleware/1212/toplink/TLADG/websphere.htm

Resources