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

Spring无法注入实体管理器工厂

魏誉
2023-03-14
@Repository
public class GenericDAOImpl implements GenericDAO {

    @PersistenceContext(unitName="unitname")
    private EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }


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

    // NullPointerException when calling this, entityManager is null
    public Query createNamedQuery(String name) {
        return entityManager.createNamedQuery(name);
    }        

    // many other methods....
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/com/main/resources/root-context.xml", "/com/main/resources/servlet-context.xml"})
public class TestModel {

    @Before
    public void setUp() throws Exception{
        ...
    }

    @Test
    public void test(){
        ...
    }
}
<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:beans="http://www.springframework.org/schema/beans" 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/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        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-3.0.xsd
        "
>

    <!-- Root Context: defines shared resources visible to all other web components -->

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="unitname" />
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.main" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="generateDdl" value="false" />
                <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
            </bean>
        </property>
    </bean>

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

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />



    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false" />
    <context:component-scan base-package="com.main" />
    <context:annotation-config />

</beans>

编辑:堆栈跟踪如下:

java.lang.NullPointerException
    at com.main.model.dao.JPAImpl.GenericDAOImpl.createNamedQuery(GenericDAOImpl.java:119)
    at com.main.model.bo.DescriptorBO.persist(DescriptorBO.java:52)
    at com.main.webmodule.JSONSerializer.deserialize(JSONSerializer.java:149)
    at com.main.tests.TestModel.test(TestModel.java:86)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

下面是persistence.xml:

<?xml version="1.0" encoding="UTF-8"?><persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="unitname" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <mapping-file>META-INF/jpql/NamedQueries.xml</mapping-file>


        <class>com.main.model.Account</class>
        <class>com.main.model.Action</class>
        <class>com.main.model.Device</class>
        <class>com.main.model.DeviceDescriptor</class>
        <class>com.main.model.Event</class>
        <class>com.main.model.File</class>
        <class>com.main.model.Rule</class>
        <class>com.main.model.StateVar</class>
        <class>com.main.model.Argument</class>
        <exclude-unlisted-classes>false</exclude-unlisted-classes> 


        <properties>

            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="root"/>
            <property name="hibernate.connection.provider_class" value="org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" />
            <property name="hibernate.connection.autocommit" value="true"/>
            <property name="hibernate.connection.release_mode" value="auto"/>
            <property name="hibernate.connection.url" value="jdbc:mysql://127.0.0.1:3306/testweb"/>
            <property name="hibernate.hbm2ddl.auto" value="create"/>

            <property name="hibernate.c3p0.min_size" value="1" />
            <property name="hibernate.c3p0.max_size" value="10" />
            <property name="hibernate.c3p0.acquire_increment" value="1" />
            <property name="hibernate.c3p0.idle_test_period" value="300" />
            <property name="hibernate.c3p0.max_statements" value="0" />
            <property name="hibernate.c3p0.timeout" value="100" />

            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>

        </properties>




    </persistence-unit>
</persistence>

共有1个答案

徐帅
2023-03-14

我终于设法解决了这个问题。为了实例化GenericDAO,我使用了autowired注释,如下所示:

@Autowired
private GenericDAO genericDao;

但是发生这种情况的类DescriptorBO是这样实例化的:

DescriptorBO descrBO = new DescriptorBO(...);

从而完全脱离了Spring容器的控制。将此更改为:

@Autowired
private DescriptorBO descrBO;
<bean name="descriptorBO" class="com.main.model.bo.DescriptorBO">
    <property name="genericDao" ref="genericDao" />
</bean>

<bean name="genericDao" class="com.main.model.dao.JPAImpl.GenericDAOImpl" /> 
 类似资料:
  • 问题内容: 一个很长的问题,请忍受我。 我们将Spring + JPA用于Web应用程序。我的团队在讨论如何在注入的(基于泛型的东西对AppFuse中提供的线DAO,我们不使用过的注射某种原因)。我们正在使用“应用程序管理的持久性”。 反对注入a的论点是它太重了,因此不是必需的,这就是我们需要的。而且,由于Spring将为每个Web请求创建一个DAO的新实例(我对此表示怀疑),因此不会有任何并发​

  • 我试图使用spring boot将EntityManager注释注入到我的DAO中,但是得到一个< code > InvalidDataAccessApiUsageException 消息,说没有可用的事务EntityManager。我的印象是,只要Spring Boot从< code>application.yml中获得了我的数据源信息,并且我用< code>@PersitenceContext

  • 我刚刚开始使用Spring ROO,并使用数据库逆向工程命令生成了我的实体类。然而每当我试图调用生成的实体类中的一个CRUD方法时,我总是得到这个异常:Java . lang . illegalstateexception:实体管理器没有被注入(Spring Aspects JAR是否被配置为AJC/AJDT方面库?) 我怀疑(通过查看生成的文件)EntityManager没有被注入到类中。你能告

  • 我有一个在Eclipse中定义的非常基本的JavaEE应用程序(一个EJB,一个带有PrimeFaces的网页,一个JPA实体)。它有四个项目,一个用于EAR,一个用于EJB,一个用于JPA,一个用于Web部件。问题是,我试图在JPA项目的persistence.xml中配置HiberNate作为持久化框架,但它并没有像我预期的那样完全工作。在我的EJB(@Statless)中,我可以通过两种方式

  • 问题内容: 我在JavaFx fxml应用程序中都使用了数据库中的Persistence单元和Entity类,我已成功将所有表作为实体导入到Model中,问题是当我尝试插入实体时出现异常和错误,这是我的整个代码 这是当我按下按钮时(当handleButtonAction被触发时)我得到的全部错误。 我在已经存在的类似问题中找不到答案,无法确切知道我所缺少的内容,在此先感谢您的帮助。 问题答案: 为

  • 我对EJB的概念非常陌生。我正在尝试使用实体类将前端的值插入到数据库中,但每次我这样做时,我都会收到此错误: 这是我的实体类: 我使用的是seam 2.2.1、EJB 3和Oracle 10g。 请帮助我解决此错误。