修复Spring MVC应用程序中的Null EntityManager?

时间:2009-05-20 15:20:35

标签: java spring jpa spring-mvc entitymanager

在下面的代码中,我注入了EnitityManager,其中始终显示为null ;

public class GenericController extends AbstractController {

    @PersistenceContext(unitName = "GenericPU")
    private EntityManager em;

    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        //(em == null) is always trigged
        if (em == null) throw new NullPointerException("em is null");
        Collection<Generic> Generics = em.createNamedQuery("Generic.findAll").getResultList();

        ModelAndView mav = new ModelAndView("Generic");
        mav.addObject(Generics); 
        return mav;
    }
}

这是bean定义,在 dispatcher-servlet.xml 中定义。

<bean id="Generic" class="com.application.web.GenericController" />

应该基于tx:annotation注入EnitityManager,在 persistence-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-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
        <property name="url" value="removed" />
        <property name="username" value="removed" />
        <property name="password" value="removed" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="GenericPU" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>
        <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.SQLServerDialect" />
            </bean>
        </property>
    </bean>

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

    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

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

</beans> 

持久性上下文是从 applicationContext.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-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">    
    <import resource="classpath:META-INF/persistence-context.xml"/>
</beans>

完成类路径导入是因为ORM实体作为JAR文件包含在项目中。请注意,我相信正在加载持久性上下文,因为如果无法解析其配置文件,Spring将不允许部署该应用程序。

这是我的 persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
  <persistence-unit name="CoolOrmJpaPU" transaction-type="RESOURCE_LOCAL">
    <class>com.application.orm.jpa.Generic</class>
    <!-- bunch more classes -->
  </persistence-unit>
</persistence>

我的 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

有人可以帮助我吗?

4 个答案:

答案 0 :(得分:8)

今天我很幸运能够和一位顾问谈论这个问题,他能够帮助我解决整个问题。

所以我的问题是Spring MVC正在建立两个不同的上下文,一个在applicationContext.xml中定义的应用程序上下文和一个在dispatcher-servlet.xml中定义的Web上下文。

来自一个上下文的Bean无法与另一个上下文中的bean通信,因此当我在applicationContext.xml中启动我的持久化上下文时,我无法在由dispatcher-servlet.xml加载的bean中访问它,即我的控制器。

当Netbeans自动为我的Spring MVC生成基础时,它默认设置它。在一些大型Web应用程序中,将应用程序的Web部分与其他逻辑(持久性,业务代码等)区分开来是有意义的。在我的情况下,我试图将我的实体经理直接自动注入我的控制器,这对我不利。

要解决此问题,请移动

<import resource="classpath:META-INF/persistence-context.xml"/>

从applicationContext.xml到我的dispatcher-servlet.xml。然后我的控制器从@PersistanceContext注释中正确地注入了EntityManagers。

答案 1 :(得分:0)

你有没有

<context:annotation-config />

在你的spring XML中。参考here

答案 2 :(得分:0)

我认为您需要一个文件persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">

  <persistence-unit name="GenericPU">
     <class>com.domain.MyClass</class>
  </persistence-unit>

</persistence>

我认为如果文件名称不同,它将无效,尤其是因为您没有告诉EntityManager工厂任何地方的新名称。

答案 3 :(得分:0)

我曾经使用过较旧的spring版本,当你必须将setProperty()放到bean中并在spring-bean定义中设置propery标签时:

<bean id="Generic" class="com.application.web.GenericController" />
    <property name="em" ref="entityManager" />
</bean>

也许您应该使用transactionManager或entityManagerFactory bean ...

PD:我个人更喜欢旧的注入依赖关系的方式。