2014-10-02 4 views
2

Я работаю на весну и спящий режим, я получаю это следующее исключение, которое я не могу отлаживатьНе удалось получить экземпляр EntityManager?

Ниже StackTrace ошибка:

SLF4J: Не удалось загрузить класс «org.slf4j.impl.StaticLoggerBinder ». SLF4J: Реализация регистратора без операции (NOP) SLF4J: См. http://www.slf4j.org/codes.html#StaticLoggerBinder для получения дополнительной информации. 2 октября 2014 7:07:13 PM

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons 
INFO: Destroying singletons in org.s[email protected]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 

Ниже мой фрагмент кода:

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> 

Ниже мой файл конфигурации пружины [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 Класс, который будет реализовывать интерфейс StudentDAO, будет иметь методы, такие как

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

    } 

Наконец главный класс

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()); 
      } 
     } 
    } 

Пожалуйста, попробуйте помочь мне.

Любые ответы высоко оценены

ответ

1

Ответ на этот вопрос должен применяться и здесь: EntityManager and persist method not working properly

Короче: Удалить

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

из определения вашего studentDAO-бобов в SpringBeans.xml. Он уже вводится через сканирование компонентов.

+0

Теперь его рабочий sheltem. большое спасибо. – VSK

Смежные вопросы