当前位置: 首页 > 知识库问答 >
问题:

ClassCastException:org。冬眠impl。SessionImpl无法强制转换到引擎。spi。SessionImplementor

龚国源
2023-03-14

在通过POST addUser方法将表单提交给UserController时,将调用该方法,但在其第2行

 userService.addEmployee(user);

发生异常stacktrace为

组织。springframework。网状物util。NestedServletException:请求处理失败;嵌套的异常是org。springframework。交易CannotCreateTransactionException:无法为事务打开Hibernate会话;嵌套的异常是java。lang.ClassCastException:org。冬眠impl。SessionImpl无法强制转换为组织。冬眠发动机spi。SessionImplementor组织。springframework。网状物servlet。FrameworkServlet。processRequest(FrameworkServlet.java:894)org。springframework。网状物servlet。FrameworkServlet。doPost(FrameworkServlet.java:789)javax。servlet。http。HttpServlet。服务(HttpServlet.java:710)javax。servlet。http。HttpServlet。服务(HttpServlet.java:803)

根本原因

com.example.model.User@7544ae20Feb 26,2015 4:51:02 PMorg.apache.catalina.core.Standard WrapperValve调用SEVERE: Servlet.service()对于servlet调度Servlet抛出异常java.lang.ClassCastExcture:org.hibernate.impl.SessionImpl不能强制转换为<--plhd-org.springframework.orm.hibernate4.HibernateTransactionManager.do开始(HibernateTransactionManager.java:354)在org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)在org.springframework.transaction.interceptor.TransactionAupport.createTransactionIfNecessary(TransactionAupport.java:335)在org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)在org.springframework.aop.framework.Reflropemethod odInvocation.proceed(Reflropemethod odInvocation. java: 172)在org. springframework. aop. framework.jdkDynamicAopProxy. invoke(JdkDynamicAopProxy. java: 202)在com. sun. proxy。$Proxy17. add雇员(未知来源)在com. list. Controler。UserController. addUser(UserController. java: 33)在sun.反射。nativemethod odAccessorImp. invke0(本机方法)在sun.反射。nativeMEDAccessorInp. invoke(NativeMEDAccessorInp. java: 57)在sun. reff。在java. lang.反射中调用(委托方法访问或执行. java: 43)。在org. springframework. web. method. support上调用(method. java: 606)。在org. springframework. web. method. support上调用(InvocableHandlerWay. java: 213)。在org. springframework. web. servlet. mvc. method. annote上的InvocableHandlerWay. InvocableHandlermethod.在org. springframework. web. servlet. mvc. method.注解中,ServletInvocableHandlerWay. invkeAndHandle(ServletInvocableHandlermethod. java: 96)。在org. springframework. web. servlet. mvc. method.注释中请求MappingHandlerAdapter。在org. springframework. web. servlet. mvc. method.中,请求MappingHandlerAdapter. handle内部(请求MappingHandlerAdapter. java: 578)。在org. springframework. web. servlet中处理(AbstractHandlerMEDAdapter. java: 80)。在org. springframework. web. servlet上发送(DispatcherServlet. java: 923)。DispatcherServlet. doService(DispatcherServlet. java: 852)在org. springframework. web. servlet。在org. springframework. web. servlet上的FrameworkServlet.过程请求(FrameworkServlet. java: 882)。doPost(FrameworkServlet. java: 789)在javax. servlet. http.服务(HttpServlet. java: 710)在javax. servlet. http.服务(HttpServlet. java: 803)在org. apache. catalina. core。在org. apache. catalina. core上的Application ationFilterChain. interalDoFilter(Application ationFilterChain. java: 290)。在org. apache. catalina. core上的Application ationFilterChain. doFilter(Application ationFilterChain. java: 206)。在org. apache. catalina. core上调用(标准WrapperValve. java: 230)。在org. apache. catalina. core上调用(Standard ContextValve. java: 175)。在org. apache. catalina. valves. invoke(Standard HostValve. java: 128)。在org. apache. catalina. core上调用(ErrorReportValve. java: 104)。在org. apache. catalina.连接器上调用标准工程师。coyoteAdapter. service(CoyoteAdapter. java: 261)在org. apache. coyot. http 11.进程(Http11Processor. java: 844)在org. apache. coyot. http 11.http://www. org. apache. tomcat. util. net的处理程序(http://www. ttp11ConnectionHandler. org. apache. tomcat. util. net.JIoEndpoint$Worker. run(JIoEndpoint. java: 447)at java. lang.线程.运行(线程. java: 744)

用户控制器

@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>

 @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;
}

}

为什么这个例外会到来。请解释一下。

提前谢谢。

共有2个答案

刘选
2023-03-14

问题是中的Spring配置文件

正在更改为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>

应涵容
2023-03-14

您使用的是哪个版本的Spring?

为什么HibernateTransactionManagerAnnotationSessionFactoryBean来自不同的包?

你可以从同一个包装使用和尝试。

 类似资料:
  • 我得到以上的错误,如果有人知道,然后告诉我。。。我将非常感激 Java: XML:

  • 下面是托管活动片段: 有问题的行是代码段的最后一行。这是我的语录片段。 假设我对主机活动没有扩展support.v4的看法是正确的,那么我该怎么做呢?

  • 我使用Nashorn与Java制作一个模块化插件系统。插件将使用Javascript编写。一个重要的特性是具有可以用Javascript代码编写的处理程序。一开始,我的目标是制作一个简单的命令系统。javascript实现一个接口,并调用Java方法来注册命令。然而,我得到一个错误。我确保我使用的是Nashorn()返回true。 Javascript: Java代码:调用“侦听”: 其中'f'是

  • 问题内容: 应用程序版本: JBoss 7.0.0,Oracle 11g(ojdbc6.jar)和JDK 6版本 当我尝试使用函数插入CLOB数据类型的值时遇到问题,出现以下异常。 在多个论坛中搜索后,未找到任何解决方案。 https://forums.oracle.com/forums/thread.jspa?threadID=279238 完成了部署WAR文件和配置JBoss oracle驱动

  • 问题内容: 尝试将结果集强制转换为映射类时,我收到了hibernate类的类强制转换异常…我能够查看返回的结果集中的数据…但是它以Object []的形式返回我可以将Object []设置为List …我可以正确地进行hibernate映射吗?我从查询中获取了正确的数据,但映射不正确… 映射 映射类 参加班 主要 问题答案: 对于测试,我建议您在产生类强制转换异常的语句周围放置一个try-catc