Spring 4 + Hibernate 5 = org.springframework.orm.jpa.EntityManagerHolder 不能转换为 org.springframework.o

Posted

技术标签:

【中文标题】Spring 4 + Hibernate 5 = org.springframework.orm.jpa.EntityManagerHolder 不能转换为 org.springframework.orm.hibernate5.SessionHolder【英文标题】:Spring 4 + Hibernate 5 = org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder 【发布时间】:2016-12-02 07:43:32 【问题描述】:

好的,我是一个完整的初学者,开始一个新的java项目并集成spring/hibernate等工具。事实上,这是我第一次这样做。所以我相信这个错误对你们来说是显而易见的。

猜测:

我期望的会话工厂不是spring注入的。 错误的依赖关系。

错误

[2016-07-28 01:29:14.869] boot - 22234 ERROR [http-nio-8080-exec-1] --- [dispatcherServlet]: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder] with root cause
    java.lang.ClassCastException: org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder
        at org.springframework.orm.hibernate5.HibernateTransactionManager.doGetTransaction(HibernateTransactionManager.java:376)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.pse</groupId>
    <artifactId>plataforma-ejercicios</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <org.springframework.version>4.3.1.RELEASE</org.springframework.version>
        <spring-boot-starter.version>1.3.5.RELEASE</spring-boot-starter.version>
        <org.hibernate.version>5.2.0.Final</org.hibernate.version>
        <mysql-connector-java.version>5.1.38</mysql-connector-java.version>
        <c3p0.version>0.9.1.2</c3p0.version>
    </properties>


    <dependencies>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>$c3p0.version</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>$org.springframework.version</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.1.3.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>5.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.1.0.Final</version>
        </dependency>

        <!-- Maria -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>1.1.7</version>
        </dependency>


        <!-- Spring framework -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>$org.springframework.version</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Spring boot -->
         ....
           ...
    </dependencies>

</project>

base-context.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-4.3.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <import resource="classpath:hibernate-context.xml" />
    <context:property-placeholder location="classpath:hibernate.properties" />

    <bean id="studentDAO" class="org.pse.plataformaejercicios.dao.StudentDAO">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

hibernate-context.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:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="$hibernate.connection.driver_class" />
        <property name="jdbcUrl" value="$hibernate.connection.url" />
        <property name="user" value="$hibernate.connection.username" />
        <property name="password" value="$hibernate.connection.password" />
        <property name="minPoolSize" value="$hibernate.connection.min_pool_size" />
        <property name="maxPoolSize" value="$hibernate.connection.max_pool_size" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="c3p0DataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan" value="org.pse.plataformaejercicios.model" />

    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

hibernate.properties

hibernate.dialect org.hibernate.dialect.MySQL5Dialect
hibernate.connection.driver_class org.mariadb.jdbc.Driver
hibernate.connection.url jdbc:mariadb://127.0.0.1:3306/pse
hibernate.connection.username pse
hibernate.connection.password passpse
hibernate.connection.min_pool_size 2
hibernate.connection.max_pool_size 10
hibernate.connection.autocommit true
hibernate.hbm2ddl.auto update
hibernate.show_sql true

StudentController.java

@RestController
public class StudentController 

    private Logger logger = LoggerFactory.getLogger(StudentController.class);

    private StudentService studentService;

    @RequestMapping(value = "/student/studentId/classes", method = RequestMethod.GET)
    public ClassDTO getClassesForStudent()
        return new ClassDTO();
    

    @RequestMapping("/saveStudent/nombre/apellido")
    public void saveStudent(@PathVariable String nombre, @PathVariable String apellido) 
        logger.info("Entrada al controller de: TestHibernate");

        Student student = new Student();
        student.setLastName(apellido);
        student.setName(nombre);

        studentService.save(student);
    


    @Autowired
    public void setStudentService(StudentService studentService) 
        this.studentService = studentService;
    


StudentServiceImpl.java

@Service
public class StudentServiceImpl implements StudentService 

    private StudentDAO studentDAO;

    @Override
    @Transactional(readOnly = false)
    public void save(Student student) 
        studentDAO.save(student);
    

    @Autowired
    public void setStudentDAO(StudentDAO studentDAO) 
        this.studentDAO = studentDAO;
    

StudentDAO.java

public class StudentDAO 

    private SessionFactory sessionFactory;

    public void save(Student student)
        try 
            Session session = sessionFactory.getCurrentSession();
            session.save(student);
         catch (Exception e) 
            e.printStackTrace();
        
    

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) 
        this.sessionFactory = sessionFactory;
    


【问题讨论】:

对于初学者停止混合休眠版本hibernate-corehibernate-entitymanager 应该有相同的版本,他们没有。 【参考方案1】:

你使用 Spring-Boot 吗?是这样的,就我而言,问题出在@EnableAutoConfiguration - 使用 exclude=HibernateJpaAutoConfiguration.class

【讨论】:

这就是问题所在!非常感谢! =D 你知道为什么会导致这个问题吗? 还没有 :( 但我要调查一下。 @Victor Krapivin 有效,非常感谢!你找到原因了吗? 我删除了与Entity和Hibernate无关的服务函数上的@Transactional注解。我用它来调用远程服务api。这解决了问题。 代码为:@EnableAutoConfiguration(exclude = HibernateJpaAutoConfiguration.class )

以上是关于Spring 4 + Hibernate 5 = org.springframework.orm.jpa.EntityManagerHolder 不能转换为 org.springframework.o的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 1.5.x 与 Hibernate 4.x 的兼容性

在Spring(4.3.22)中集成Hibernate(5.4.0)

将 Spring 应用程序从 Hibernate 4.3.1.Final 迁移到 5.4.27.Final

Spring ORM 4.0.5 和 Hibernate 4.3.5 - 无法保存到数据库

在树脂服务器上使用 Hibernate 5.4.1 的 Spring 5.0.7

Spring 4,Websphere 8.5.5 上的 Hibernate JPA JarInputStreamBasedArchiveDescriptor 错误