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

无法获取EntityManager的实例?

龙珂
2023-03-14
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
<?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>

下面是我的spring配置文件[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>

我的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个答案

齐建安
2023-03-14

这个问题的答案也应该适用于这里:EntityManager和Persisted方法不能正常工作

简而言之:移除

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

springbeans.xml中studentDAO-bean的定义可以看出。它已经通过组件扫描注入。

 类似资料:
  • 我们使用nextjs/reactjs作为FE,并且我们有一个server.js文件,它允许我们在上传映像,但是由于某种原因,每当我们运行服务器时,都会出现错误 下面是我们在server.js上的代码 这些是我们package.json中包含的脚本 希望得到一些答案和建议。这些代码在本地运行,没有任何问题

  • 我使用Spring靴,希望提高性能。我必须下载数据库中有50000个字段的文件。使用hibernate。我在批量插入中找到了解决方案。但我不知道如何从Crudepository获得entitymanager 我创建了MyStorageService并想保存我的文件: } 如果在MyStorageService中使用 我明白了 错误[http-nio-18842-exec-1]JpaTransact

  • 我有下一个问题: 但是尝试这个会发送给我这个错误: Usuario no creado错误:javax.Persistence.persistenceException:Exception[EclipseLink-7060](Eclipse Persistence Services-2.5.v20140319-9AD6ABD):org.Eclipse.Persistence.exceptions.

  • 是否有任何方法可以获取给定实体对象的EntityManager句柄?我将spring boot 1.2.3与JPA starter一起使用,并使用配置进一步明确配置多个数据源 我检查了[解决]SPRING BOOT访问entityManager,它似乎没有回答这个问题。 谢谢。 编辑:我添加了如何定义数据源的说明: 在我的应用程序中。yml我有以下部分 到目前为止,我已经尝试了@Stephane的

  • https://graph.microsoft.com/v1.0/groups/{groupId}?$select=可见性 同样,在我们的应用程序中,它使用Sharepoint SPFx和HttpClient,它当前返回了400个相同URL的错误请求。

  • 将android Studio更新到3.1后,我的项目未编译。与Gradle同步时显示错误。 javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException: PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到