복붙노트

[SPRING] 스프링 MVC 애플리케이션에서 Null EntityManager 수정?

SPRING

스프링 MVC 애플리케이션에서 Null EntityManager 수정?

다음 코드에서는 항상 주입 된 EntityManager에 문제가 있습니다. 항상 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;
    }
}

다음은 dispatcher-servlet.xml에 정의 된 bean 정의입니다.

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

EnitityManager는 persistence-context.xml 파일에 정의 된 tx : annotation-based를 기반으로 삽입해야합니다.

<?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> 

persistence-context는 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>

누구든지 나를 도울 수 있습니까?

해결법

  1. ==============================

    1.이 문제에 대해 컨설턴트와 이야기 할 수있을만큼 운이 좋았습니다. 그는 모든 것을 정리할 수있었습니다.

    이 문제에 대해 컨설턴트와 이야기 할 수있을만큼 운이 좋았습니다. 그는 모든 것을 정리할 수있었습니다.

    그래서 제 문제는 Spring MVC가 applicationContext.xml에 정의 된 하나의 응용 프로그램 컨텍스트와 dispatcher-servlet.xml에 정의 된 하나의 웹 컨텍스트라는 두 개의 별개의 컨텍스트를 설정한다는 것입니다.

    하나의 컨텍스트에서 콩은 다른 컨텍스트에서 콩 이야기 수 없습니다, 따라서 내가 applicationContext.xml 내에서 내 지속성 컨텍스트를 초기화, 나는 콩을 dispatcher - servlet.xml, 즉 내 컨트롤러에 의해로드에 액세스 할 수 없습니다.

    넷빈즈가 스프링 MVC에베이스를 자동으로 생성 할 때 Netbeans는 기본적으로이를 설정합니다. 일부 대형 웹 응용 프로그램에서는 나머지 논리와 다른 컨텍스트 (지속성, 비즈니스 코드 등)로 응용 프로그램의 웹 파트를 구분하는 것이 좋습니다. 필자의 엔티티 관리자를 컨트롤러에 직접 삽입하려고하는 나의 경우에는 이것이 나에게 맞았다.

    문제를 해결하기 위해이 줄을 옮겼습니다.

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

    applicationContext.xml에서 내 dispatcher-servlet.xml. 그런 다음 컨트롤러에 @PersistanceContext 주석의 EntityManagers가 제대로 주입되었습니다.

  2. ==============================

    2.파일 persistence.xml이 필요하다고 생각합니다.

    파일 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. ==============================

    3.저는 오래된 스프링 버전으로 작업 했었습니다. setProperty ()를 bean에 넣고 spring-bean 정의 안에 propery 태그를 설정해야 할 때 :

    저는 오래된 스프링 버전으로 작업 했었습니다. setProperty ()를 bean에 넣고 spring-bean 정의 안에 propery 태그를 설정해야 할 때 :

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

    어쩌면 당신은 transactionManager 또는 entityManagerFactory beans로 작업해야합니다 ...

    PD : 저는 개인적으로 종속성을 주입하는 오래된 방법을 선호합니다.

  4. ==============================

    4.포함 시켰습니까?

    포함 시켰습니까?

    <context:annotation-config />
    

    봄 XML에서. 여기 참조

  5. from https://stackoverflow.com/questions/888581/fixing-null-entitymanger-in-spring-mvc-application by cc-by-sa and MIT license