javajpa-2.0spring-3hibernate3

Unable to get instance of EntityManager?


I am working on spring and hibernate, i am getting this following exception which i am unable to debug

Below is the error stacktrace:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Oct 2, 2014 7:07:13 PM

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1712b3a: defining beans [studentDAOImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,entityManagerFactory,jpaDialect,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,studentDAO,student,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
Oct 2, 2014 7:07:13 PM org.springframework.orm.jpa.AbstractEntityManagerFactoryBean destroy
INFO: Closing JPA EntityManagerFactory for persistence unit 'SHPersistenceUnit'
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentDAO' defined in class path resource [SpringBeans.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type '$Proxy10 implementing org.hibernate.ejb.HibernateEntityManagerFactory,org.springframework.orm.jpa.EntityManagerFactoryInfo' to required type 'javax.persistence.EntityManager' for property 'entityManager'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [$Proxy10 implementing org.hibernate.ejb.HibernateEntityManagerFactory,org.springframework.orm.jpa.EntityManagerFactoryInfo] to required type [javax.persistence.EntityManager] for property 'entityManager': no matching editors or conversion strategy found
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.sh.main.Main.main(Main.java:21)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type '$Proxy10 implementing org.hibernate.ejb.HibernateEntityManagerFactory,org.springframework.orm.jpa.EntityManagerFactoryInfo' to required type 'javax.persistence.EntityManager' for property 'entityManager'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [$Proxy10 implementing org.hibernate.ejb.HibernateEntityManagerFactory,org.springframework.orm.jpa.EntityManagerFactoryInfo] to required type [javax.persistence.EntityManager] for property 'entityManager': no matching editors or conversion strategy found
    at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:485)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:516)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1406)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1365)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    ... 11 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [$Proxy10 implementing org.hibernate.ejb.HibernateEntityManagerFactory,org.springframework.orm.jpa.EntityManagerFactoryInfo] to required type [javax.persistence.EntityManager] for property 'entityManager': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:241)
    at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:470)
    ... 17 more

Below is my code snippet:

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.0"
        xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
        <persistence-unit name="SHPersistenceUnit"
            transaction-type="RESOURCE_LOCAL">
            <class>com.sh.model.Student</class>

            <properties>
                <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
                <property name="hibernate.connection.username" value="VIBHU" />
                <property name="hibernate.connection.password" value="vibhu" />
                <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:XE" />
                <property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect" />
                <property name="hbm2ddl.auto" value="update" />
                <property name="show_sql" value="true" />

            </properties>
        </persistence-unit>
    </persistence>

Below is my spring configuration file [SpringBeans.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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-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/mvc
                           http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd">

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

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"></property>
        <property name="persistenceUnitName" value="SHPersistenceUnit"></property>
        <!-- <property name="jpaVendorAdapter" ref="jpaVendorAdapter"></property> -->
        <property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence"/>
        <property name="jpaDialect" ref="jpaDialect"></property>
    </bean>

    <!-- <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="database" value="ORACLE"></property>
        <property name="databasePlatform" value="org.hibernate.dialect.OracleDialect"></property>
    </bean> -->

    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"></bean>

    <tx:annotation-driven />

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"></property>
    </bean>

    <bean id="studentDAO" class="com.sh.dao.impl.StudentDAOImpl">
        <property name="entityManager" ref="entityManagerFactory"></property>
    </bean>

    <bean id="student" class="com.sh.model.Student"></bean>


</beans>

My StudentDAOImpl Class which will implements StudentDAO interface will have methods like

StudentDAO interface

public void saveStudent(final Student student);

public List<Student> getAllStudents();

public void update(final Student student);


StudentDAOImpl Class



 import java.util.List;

    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;

    import org.hibernate.Session;
    import org.springframework.stereotype.Repository;

    import com.sh.dao.StudentDAO;
    import com.sh.model.Student;

    @Repository
    public class StudentDAOImpl implements StudentDAO {

        @PersistenceContext
        private EntityManager entityManager;

        public Session getSessionObj() {
            return (Session)entityManager.getDelegate();
        }

        @Override
        public void saveStudent(final Student student) {
            // TODO Auto-generated method stub
            System.out.println("saving object state to DB");
            entityManager.persist(student);
            entityManager.getTransaction().commit();
            System.out.println("saved successfully");

        }

        @Override
        public List<Student> getAllStudents() {
            // TODO Auto-generated method stub
            System.out.println("retrieving all student details from DB");
            List list = null;
            String hql = "from Student as student";
            Query query = entityManager.createNamedQuery(hql);
            list = query.getResultList();
            System.out.println("list size from getAllStudents "+list.size());
            return list;
        }

        @Override
        public void update(final Student student) {
            // TODO Auto-generated method stub
            System.out.println("updating student object to DB");
            Session session = getSessionObj();
            session.beginTransaction();
            session.update(student);
            session.getTransaction().commit();
            System.out.println("updated successfully");

        }

        public void setEntityManager(EntityManager entityManager) {
            this.entityManager = entityManager;
        }

    }

Finally Main Class

public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("main method ");

        AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("SpringBeans.xml");
        System.out.println("next");
        Student stud = abstractApplicationContext.getBean("student", Student.class);
        stud.setStudentName("Alan");
        StudentDAOImpl studentDAOImpl = abstractApplicationContext.getBean("studentDAO", StudentDAOImpl.class);
        studentDAOImpl.saveStudent(stud);
        List list = studentDAOImpl.getAllStudents();
        if(list!= null && list.size()>0) {
            Iterator itr = list.iterator();
            while(itr.hasNext()) {
                Student student = (Student)itr.next();
                System.out.println(student.getId()+"\t"+student.getStudentName());
            }
        }
    }

Please try to help me.

Any answers are highly appreciated


Solution

  • The answer to this question should apply here as well: EntityManager and persist method not working properly

    In short: Remove

    <property name="entityManager" ref="entityManagerFactory"></property>
    

    from the definition of your studentDAO-bean in the SpringBeans.xml. It is already injected via the component scan.