有没有办法改变方法的JPA提取类型? [英] Is there a way to change the JPA fetch type on a method?

查看:124
本文介绍了有没有办法改变方法的JPA提取类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过一种方法在不编辑实体对象的情况下更改JPA提取类型?

我有一个由JPA实体类组成的共享ORM层.该ORM层由两个DAO层访问.一个DAO需要像我的Web应用程序那样进行延迟获取,而另一个DAO则需要进行快速获取,因为我需要它是线程安全的.

I have a shared ORM layer consisting of JPA entity classes. This ORM layer is accessed by two DAO layers. One DAO needs lazy fetching, as it is for my web application, the other needs eager fetching, as I need it to be threadsafe.

这是我的线程安全DAO中的示例方法,

Here is an example method from my 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();
}

我如何使这个方法(或整个类)使用渴望获取的方法?

How would I make this method (or entire class) use eager fetching?

推荐答案

我假设您的实体关联(@ OneToOne,@ OneToMany,@ ManyToOne)是懒惰的(FetchType.Lazy)

I assume that your entity associations (@OneToOne, @OneToMany, @ManyToOne) are fechted lazy (FetchType.Lazy)

然后我可以想到两种方式:

Then I can think of two ways:

A.编写两个jpa查询,第一个查询获取懒惰的关联(这是休眠的默认方式),第二个查询显式强制加载关联(请参阅查询中的"fetch"关键字).

A. write two jpa query one which fetch the association of the lazy (thats the default way for hibernate) and a second query which explicit force eager loading of association (see "fetch" keyword in query).


        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(entity)强制在检索到实体后(例如通过finder ...)强制加载该实体的惰性关系.

B. use Hibernate.initialize(entity) to force eager loading of lazy relations of an entity after you have retrieved it (e.g. through finder ...)


ErrorCode lazyCode = findErrorCodeById(1);
// eager load associations
Hibernate.initialize(lazyCode);

这篇关于有没有办法改变方法的JPA提取类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆