JPA查询返回代理实体 [英] JPA query returns proxied entities

查看:363
本文介绍了JPA查询返回代理实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有2个实体,EntityA和EntityB.
EntityB与EntityA相关的@OneToOne:

Suppose I have 2 entities, EntityA and EntityB.
EntityB is @OneToOne related to EntityA:

@Entity
public class EntityB {
    @OneToOne(fetch = FetchType.LAZY)
    private EntityA entA;

    // other stuff
}

当我从数据库加载EntityB时,相应的EntityA(例如 entA1 )被延迟加载.
之后,我通过

When I load EntityB from DB, the corresponding EntityA (say entA1) is lazy loaded.
After that I load EntityA list by

   List result = entityManager.createQuery("select A from EntityA A")
                  .setFirstResult(start).setMaxResults(end).getResultList();

结果列表包含以前的延迟加载和代理的EntityA以及正常的物化EntityAs,例如:

The result list contains both previously lazy loaded and proxied EntityA and normal materialized EntityAs such like:

EntityA
EntityA_$$_javassist_nnn   <--- entA1 which is loaded lazily earlier
EntityA
...

所以我的问题:
1)这是预期的行为吗?在哪里可以找到有关该文件的apidoc信息?
2)我可以只完全加载代理实体还是热切地加载所有实体?不混.

So my questions:
1) Is this an expected behavior? Where can I find apidoc info about that?
2) Can I entirely load proxied entities only or entirely load eagerly all of them? Not mixed.

推荐答案

是的,这是预期的行为. Hibernate会竭尽所能在会话中拥有一个实体的一个实例,并且只有一个实例.由于它已经具有在加载EntityB时存储在会话中的EntityA代理,因此后续的返回相同EntityA实例的查询实际上将返回相同的实例:该代理已存储在会话中.

Yes, it's expected behavior. Hibernate does everything it can to have one and only one instance of an entity in the session. Since it already has a proxy to EntityA, stored in the session when you loaded EntityB, a subsequent query returning the same EntityA instance effectively return the same instance: the proxy already stored in the session.

您不必在意列表中包含代理的事实.在代理上调用任何方法(getClass()除外)将返回与在未代理实体上调用它相同的结果.

You shouldn't care much about the fact that the list contains proxies. Calling any method on the proxy (except getClass()) will return the same thing as calling it on the unproxied entity.

AFAIK,尽管对象甚至没有equals()方法,但这仍然可以使实体的集合与附加对象的行为正确.

AFAIK, that's what allows having collections of entities behaving correctly with attached objects, although the objects don't even have an equals() method.

这篇关于JPA查询返回代理实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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