2011-09-16 4 views
1

이제 JPA에 대해 멍청한 질문을 할 시간입니다.@PersistenceContext 및 정적 속성

간단한 응용 프로그램이있어서 모든 항목에 대해 간단한 DAO 클래스를 만들고 싶습니다.

import java.io.Serializable; 
import java.util.List; 
import javax.persistence.EntityManager; 
import javax.persistence.PersistenceContext; 
import org.hibernate.Session; 

public class GenericDAO implements Serializable { 

public GenericDAO() { 
} 

@PersistenceContext(unitName="TestAppPU") 
public static EntityManager em; 

public static <T> void save(T smth) { 
    em.persist(smth); 
} 
public static <T> void merge(T smth) { 
    em.merge(smth); 
} 
public static <T> void remove(T smth) { 
    em.remove(smth); 
    em.flush(); 
} 

public static <T> List<T> getAll(Class<T> cls) { 
    return (List<T>) ((Session) em.getDelegate()).createCriteria(cls).list(); 
} 
} 

나는 그런 식으로 그것을 사용하려 :

testEntitys =GenericDAO.getAll(TestEntity.class); 

을하지만를 getAll()에서 "그들"에 대한 NullPointerException이 함께 분쇄, 그래서이 I로 @PersistanceContext로 설정되어 있지 않은 것 같습니다 예상했다. 내가 관리 빈에서 사용할 때 잘 작동 @PersistanceContext

: persistance.xml 잘 구성되어 같은

@ManagedBean 
@SessionScoped 
public class TestBean { 


    @PersistenceContext(unitName="TestAppPU") 
    public EntityManager em; 

...  
testEntitys = em.createQuery("select t from TestEntity t").getResultList(); 
... 

그래서 그것은 본다. 하지만 나는 GenericDAO에 em을 전달하고 싶지 않습니다.

제 질문은 (예상되는 두 번째 코드 샘플) @PersistanceContext를 사용하여 GenericDAO를 수행하는 방법이며, 실제로 가능합니까 아니면 지속성을 사용하려는 모든 빈에서 dao 클래스를 주입해야합니까?

답변

5

GenericDAOEntityManager으로 삽입하면 GenericDAO이 관리되지 않기 때문에 작동하지 않습니다. 대신 클래스가 세션 빈 또는 관리 빈인 경우 주입이 효과가있었습니다. 떨어져, 몇 가지 다른 점은 EntityManager 만들기

  • 주의 할

    는 비용이 많이 드는 작업이 아니다. 따라서 엔터티를 조작하려면 EntityManager을 필수 클래스에 삽입하고 EntityManager의 메서드를 직접 사용할 수 있습니다. (Sidenote : EM 서블릿으로의 주입은 피해야합니다.)

  • GenericDAO은별로 제공하지 않습니다. EntityManager은 이미 충분히 일반적이고 직접 사용할 수 있습니다.
  • 마지막으로 static 변수 및 메서드 사용에 대한 경고. 내가 테스트 가능성과 스레드 안전을 위해 반대하는 것이 좋습니다.

@Stateless을 사용하면 EntityManager을 DAO로 주입하는 것이 일반적입니다.

요약하면 EM을 DAO를 사용하지 않고도 엔티티 작업을 수행해야하는 클래스에 삽입 할 수 있습니다. 당신의 분리달라고하면, 당신은 은 PersistenceAnnotationBeanPostProcessor이 활성화 된 경우

0

스프링 필드와 메소드 레벨에서 모두 @PersistenceContext 주석을 이해할 수있는 DAO로 주입 EMStateless 콩을 가질 수 있습니다. 주석 - 구성 XML 요소를 응용 프로그램 컨텍스트 구성 : 는 Spring 컨텍스트를 사용하는 것이 좋습니다 명시 적은 PersistenceAnnotationBeanPostProcessor을 정의하는 대신

<!-- bean post-processor for JPA annotations --> 
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> 

.

<!-- post-processors for all standard config annotations --> 
<context:annotation-config/>