메소드에서 JPA 페치 유형을 변경하는 방법이 있습니까?
-
10-07-2019 - |
문제
엔티티 객체를 편집하지 않고 단일 메소드에서 JPA 페치 유형을 변경하는 방법이 있습니까?
JPA 엔티티 클래스로 구성된 공유 ORM 계층이 있습니다. 이 ORM 층은 두 개의 DAO 층으로 액세스됩니다. 하나의 DAO는 내 웹 응용 프로그램과 마찬가지로 게으른 페치가 필요합니다. 다른 하나는 스레드 사프가 필요하기 때문에 열망하는 가져 오기가 필요합니다.
다음은 내 threadsafe dao의 예제 방법입니다.
@PersistenceContext(unitName = "PersistenceUnit", type = PersistenceContextType.TRANSACTION)
private EntityManager em;
public ErrorCode findErrorCodeById(short id) {
return (ErrorCode) em.createNamedQuery("ErrorCode.findById").
setParameter("id", id).getSingleResult();
}
이 방법 (또는 전체 클래스)이 열렬한 페치를 사용하는 방법은 무엇입니까?
해결책
나는 당신의 엔티티 협회 (@onetoone, @onetomany, @manytoone)가 게으른 (fetchtype.lazy)라고 가정합니다.
그런 다음 두 가지 방법을 생각할 수 있습니다.
A. 게으른 연관성 (최대 절전 모드의 기본 방식)과 연관의 열망을 간주하는 두 번째 쿼리 (쿼리의 "페치"키워드 참조).
Query q = HibernateUtil.getSessionFactory().getCurrentSession() .createQuery("select c from Category as c" + " left join fetch c.categorizedItems as ci" + " join fetch ci.item as i");
B. Hibernate.initialize (엔티티)를 사용하여 엔티티의 게으른 관계를 간절히 바꾸어 놓은 후 (예 : Finder를 통해 ...)
ErrorCode lazyCode = findErrorCodeById(1); // eager load associations Hibernate.initialize(lazyCode);
다른 팁
JPA에서 페치 모드는 주석 또는 XML 매핑 파일을 통해 각 지속성 속성에 지정됩니다.
따라서 목표를 달성하는 JPA 공급 업체의 불가지론 적 방법은 각 DAO 레이어에 대해 별도의 매핑 파일을 갖는 것입니다. 불행히도 이것은 각 매핑 파일에 대해 별도의 PersistenceUnit이 필요하지만 적어도 동일한 엔티티 클래스와 동일한 JPQL 쿼리를 공유 할 수 있습니다.
코드 골격이 따릅니다.
Persistence.xml :
<persistence>
<persistence-unit name="dao-eager">
<mapping-file>orm-eager.xml</mapping-file>
</persistence-unit>
<persistence-unit name="dao-lazy">
<mapping-file>orm-lazy.xml</mapping-file>
</persistence-unit>
</persistence>
orm-Eger.xml :
<entity-mappings>
<entity class="ErrorCode">
<attributes>
<basic name="name" fetch="EAGER"/>
</attributes>
</entity>
</entity-mappings>
orm-lazy.xml :
<entity-mappings>
<entity class="ErrorCode">
<attributes>
<basic name="name" fetch="LAZY"/>
</attributes>
</entity>
</entity-mappings>
그런 다음 DAO 레이어에서 적절한 지속성 단위에 대해 EntityManagerFactory를 만드는 문제 일뿐입니다.
실제로 두 개의 매핑 파일이 필요하지 않으며, 게으르거나 열심을 엔티티의 주석으로 지정한 다음 XML 매핑 파일의 반대를 지정할 수 있습니다 (여전히 두 개의 지속성 유닛을 원할 것입니다).
위의 최대 절전 모드 솔루션보다 코드가 조금 더 높을 수 있지만 응용 프로그램은 다른 JPA 공급 업체에게 휴대 할 수 있어야합니다.
제쳐두고 OpenJPA는 FetchGroups (JDO에서 빌린 개념)를 사용하여 위의 최대 절전 모드 솔루션과 유사한 기능을 제공합니다.
마지막 경고 중 하나 인 FetchType.lazy는 JPA의 힌트이며, 제공자는 필요한 경우 열심히 행을 간절히로드 할 수 있습니다.
요청 당 업데이트되었습니다.
다음과 같은 엔티티를 고려하십시오.
@Entity
public class ErrorCode {
// . . .
@OneToMany(fetch=FetchType.EAGER) // default fetch is LAZY for Collections
private Collection myCollection;
// . . .
}
이 경우 여전히 두 개의 지속성 단위가 필요하지만 orm-lazy.xml 만 있으면됩니다. 보다 현실적인 시나리오를 반영하도록 필드 이름을 변경했습니다 (컬렉션과 블롭만이 기본적으로 fetchType.lazy를 사용합니다). 따라서 결과 orm-lazy.xml은 다음과 같습니다.
<entity-mappings>
<entity class="ErrorCode">
<attributes>
<one-to-many name="myCollection" fetch="LAZY"/>
</attributes>
</entity>
</entity-mappings>
그리고 persistence.xml은 다음과 같습니다.
<persistence>
<persistence-unit name="dao-eager">
<!--
. . .
-->
</persistence-unit>
<persistence-unit name="dao-lazy">
<!--
. . .
-->
<mapping-file>orm-lazy.xml</mapping-file>
</persistence-unit>
</persistence>
OpenJPA를 언급 한 사람은 아무도 없으므로 여기에 답변을 드리겠습니다.
OpenJPA에서 이전에 게으른 구성 컬렉션 및 필드는 아래와 같이 간절히로드 할 수 있습니다.
OpenJPAEntityManager kem = OpenJPAPersistence.cast(em);
kem.getFetchPlan().addField(Order.class, "products");
TypedQuery<Order> query = kem.createQuery(yourQuery, Order.class);
참조:http://openjpa.apache.org/builds/1.0.3/apache-openjpa-1.0.3/docs/manual/ref_guide_fetch.html
JPA2에서 나는 사용한다 엔티티 그래프, 검색하려는 관련 엔티티를 정의 할 수 있습니다.
https://docs.oracle.com/javaee/7/tutorial/persistence-entitygraphs002.htm https://docs.oracle.com/javaee/7/tutorial/persistence-entitygraphs003.htm
당신은 당신이했던 것처럼 지명 된 query를 만들고 당신은 키로 힌트를 첨부합니다. javax.persistence.loadgraph
또는 javax.persistence.fetchgraph
. 그래프에서 정의한 관련 엔티티를 검색합니다.
여기에서 "loadgraph"와 "fetchgraph"의 차이점을 찾을 수 있습니다. JPA의 엔티티 그래프에 대한 Fetch와 Load 사이의 디프 테니는 무엇입니까?