调用addUser方法但是在第二行
userService.addEmployee(user);
发生了一个例外,堆栈跟踪是
org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是org.springframework.transaction.CannotCreateTransactionException:无法打开Hibernate Session进行事务处理;嵌套异常是java.lang.ClassCastException:org.hibernate.impl.SessionImpl无法强制转换为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)
根本原因
com.example.model.User@7544ae20 2015年2月26日下午4:51:02 org.apache.catalina.core.StandardWrapperValve调用 严重:servlet dispatcherServlet的Servlet.service()引发了异常 java.lang.ClassCastException:org.hibernate.impl.SessionImpl无法强制转换为org.hibernate.engine.spi.SessionImplementor 在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) 在org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105) 在org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) 在org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) 在com.sun.proxy。$ Proxy17.addEmployee(未知来源) 在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) 在org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213) 在org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126) 在org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96) 在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617) 在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578) 在org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) 在org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) 在org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) 在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) 在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) 在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) 在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) 在org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) 在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) 在org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) 在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) 在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) 在org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) 在org.apache.coyote.http11.Http11Protocol $ Http11ConnectionHandler.process(Http11Protocol.java:581) 在org.apache.tomcat.util.net.JIoEndpoint $ Worker.run(JIoEndpoint.java:447) 在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配置文件是
<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();
}
}
模型
@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;
}
}
为什么会出现这种异常。请解释一下。
提前致谢。
答案 0 :(得分:1)
您使用的是哪个版本的Spring?
为什么来自不同套餐的HibernateTransactionManager
和AnnotationSessionFactoryBean
?
您可以使用相同的包装并尝试。
答案 1 :(得分:1)
问题是<bean id="sessionFactory">
中的Spring配置文件,它使用hibernate3而<bean id="hibernateTransactionManager"
使用hibernate4。
更改为hibernate4新配置文件。
Spring配置文件是
<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>