1
votes

on submitting form to UserController via POST addUser method is invoked but on its 2nd line

 userService.addEmployee(user);

a exception is occurred stacktrace is

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 java.lang.ClassCastException: org.hibernate.impl.SessionImpl cannot be cast to org.hibernate.engine.spi.SessionImplementor org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) javax.servlet.http.HttpServlet.service(HttpServlet.java:710) javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

root cause

com.example.model.User@7544ae20 Feb 26, 2015 4:51:02 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet dispatcherServlet threw exception java.lang.ClassCastException: org.hibernate.impl.SessionImpl cannot be cast to org.hibernate.engine.spi.SessionImplementor at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:354) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371) at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:335) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at com.sun.proxy.$Proxy17.addEmployee(Unknown Source) at com.example.controler.UserController.addUser(UserController.java:33) 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.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.doPost(FrameworkServlet.java:789) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:744)

UserController

@Controller
@RequestMapping("/users")
public class UserController {

@Autowired
UserService userService;

@RequestMapping(method = RequestMethod.GET, params = "new")
public String addUser(Model model) {
    model.addAttribute(new User());
    return "users/edit";
}

@RequestMapping(method = RequestMethod.POST)
public String addUser(User user, BindingResult bindingResult) {
    System.out.println(user);
    userService.addEmployee(user);
    System.out.println(user);
    return "redirect:/users/" + user.getEmpName();
}
}

UserServiceImpl

@Service("employeeService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class UserServiceImpl implements UserService {

@Autowired
private UserDao userDao;

@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addEmployee(User employee) {
    userDao.addEmployee(employee);
}

public List<User> listEmployeess() {
    return userDao.listEmployeess();
}

public User getEmployee(int empid) {
    return userDao.getEmployee(empid);
}

public void deleteEmployee(User employee) {
    userDao.deleteEmployee(employee);
}

}

Spring configuration file is

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-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.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">

<context:component-scan base-package="com.example" />

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<mvc:resources mapping="/**" location="/resources/" />

<mvc:annotation-driven />

<context:property-placeholder location="classpath:resources/database.properties" />

<tx:annotation-driven transaction-manager="hibernateTransactionManager" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${database.driver}" />
    <property name="url" value="${database.url}" />
    <property name="username" value="${database.user}" />
    <property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
        <list>
            <value>com.example.model.User</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
        </props>
    </property>
</bean>

<bean id="hibernateTransactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

DAO

 @Repository
 public class UserDaoImpl implements UserDao {

private SessionFactory sessionFactory;

@Autowired
public UserDaoImpl(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

public void addEmployee(User employee) {
    sessionFactory.getCurrentSession().saveOrUpdate(employee);
}

@SuppressWarnings("unchecked")
public List<User> listEmployeess() {
    return (List<User>) sessionFactory.getCurrentSession()
            .createCriteria(User.class).list();
}

public User getEmployee(int empid) {
    return (User) sessionFactory.getCurrentSession().get(User.class, empid);
}

public void deleteEmployee(User employee) {
    sessionFactory
            .getCurrentSession()
            .createQuery(
                    "DELETE FROM Employee WHERE empid = "
                            + employee.getEmpId()).executeUpdate();
}

}

Model

@Entity
 @Table(name="User")
 public class User implements Serializable{

private static final long serialVersionUID = -723583058586873479L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "empid")
private Integer empId;

@Column(name="empname")
private String empName;

@Column(name="empaddress")
private String empAddress;

@Column(name="salary")
private Long salary;

@Column(name="empAge")
private Integer empAge;

public Integer getEmpId() {
    return empId;
}

public void setEmpId(Integer empId) {
    this.empId = empId;
}

public String getEmpName() {
    return empName;
}

public void setEmpName(String empName) {
    this.empName = empName;
}

public String getEmpAddress() {
    return empAddress;
}

public void setEmpAddress(String empAddress) {
    this.empAddress = empAddress;
}

public Long getSalary() {
    return salary;
}

public void setSalary(Long salary) {
    this.salary = salary;
}

public Integer getEmpAge() {
    return empAge;
}

public void setEmpAge(Integer empAge) {
    this.empAge = empAge;
}

}

why this exception is coming. Please explain.

Thanks in advance.

2
could u pls post more of this stacktrace? the root cause part?Paul John
@Amogh posted UserDaoImpl which implemented class of UserDao Interfacekartikag01
@PaulJohn Root cause is what i have postedkartikag01

2 Answers

1
votes

Which version of Spring are you using?

Why HibernateTransactionManager and AnnotationSessionFactoryBean from different packages?

Can you use from same package and try.

1
votes

Problem is of Spring configuration file in <bean id="sessionFactory"> it uses hibernate3 while <bean id="hibernateTransactionManager"uses hibernate4.

Changing to hibernate4 new Configuration file.

Spring configuration file is

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-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.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">

<context:component-scan base-package="com.example" />

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<mvc:resources mapping="/**" location="/resources/" />

<mvc:annotation-driven />

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>/WEB-INF/properties/database.properties</value>
        </list>
    </property>
</bean>

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.user}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.example.model" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
        </props>

    </property>
</bean>


<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>