JPA-仅对给定查询强制延迟加载 [英] JPA - Force Lazy loading for only a given query

查看:192
本文介绍了JPA-仅对给定查询强制延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅针对给定的NamedQuery强制执行延迟加载策略.

How do i enforce lazy loading strategy just for a given NamedQuery.

例如考虑下面的伪代码(只是为了解释这种情况) 我有一个实体

for eg. Consider the below pseudo code (just to explain the case) I have an entity

@Entity
class Xyz {
 int a;
 int b;

@Fetch = EAGER
 Set<ABC> listOfItems;
}

在这种情况下,我们已声明要轻松获取listOfItems.

In this case, we have declared listOfItems to be EAGERLY fetched.

现在假设,我有一个NamedQuery (query="getXyz" , name="select x from Xyz x where a=?") 对于此查询,我只需要使结果懒惰即可,即我不希望检索listOfItems.

Now suppose , I have an NamedQuery (query="getXyz" , name="select x from Xyz x where a=?") For this query , i just need the result to be lazy i.e i dont want the listOfItems to be retrieved.

我可以通过哪些方式实现这些目标? ps: 1.我不想在Entity类中将listOfItems更改为Lazy 2.我不想选择查询中的特定字段,例如name="select a,b from Xyz z where a = ? "

What are the ways by which i can acheive them ? p.s : 1. I dont want to change the listOfItems to be Lazy in the Entity class 2. I dont want to select specific fields in the query like name="select a,b from Xyz z where a = ? "

预先感谢您的建议

推荐答案

如果您不想急于获取Set,则必须将其定义为惰性.但是请注意,当您指定lazy时,允许热切地获取实现.

If you don't want to fetch the Set eagerly you have to define it as lazy. However note that the implementation is permitted to fetch eagerly when you specify lazy.

引用规范:

公共枚举FetchType 扩展java.lang.Enum

public enum FetchType extends java.lang.Enum

定义从数据库中获取数据的策略. EAGER策略是对持久性提供程序运行时的要求,必须热切地获取数据. LAZY策略向持久性提供程序运行时提供了一个提示,即在首次访问数据时应延迟获取数据.允许该实现热切地获取已为其指定LAZY策略提示的数据.

Defines strategies for fetching data from the database. The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified.

但是,如果您不想获取这样的Set,我可以选择创建一个小型类来满足您的需求:

If you however don't want to fetch such a Set I would as an alternative create a small class to fit your needs:

@Entity
@Table(name = "XYZ")
public class XyzStub
{
    int a;
    int b;
}

您可以使用TypedQuery对此进行查询:

You can query for this using a TypedQuery:

EntityManager em;
//....
TypedQuery<XyzStub> q = em.createNamedQuery("select x from XyzStub x where x.a = :a", XyzStub.class)
q.setParameter("a", a);

这篇关于JPA-仅对给定查询强制延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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