Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 4 + Hibernate 5 = org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder

OK, I'm a complete beginner when it comes to start a new java project and integrate tools like spring/hibernate, etc. In fact, this is the first time I'm doing it. So I'm sure the error will be obvious for you guys.

Guessings:

  • The session factory I expected is not the one being injected by spring.
  • Wrong dependencies.

Error

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

}
like image 278
mjuanes Avatar asked Jul 28 '16 05:07

mjuanes


1 Answers

Do you use Spring-Boot? Is so, in my case the problem was with @EnableAutoConfiguration - use exclude=HibernateJpaAutoConfiguration.class

like image 181
Victor Krapivin Avatar answered Nov 02 '22 16:11

Victor Krapivin