[英]How can I tell if a Hibernate 4 entity is a proxy or the actual entity?
I am using Hibernate 4, with lazy loading enabled. 我正在使用Hibernate 4,并启用了延迟加载。 I have a basic entity that contains references to other objects.
我有一个基本实体,其中包含对其他对象的引用。 Below is a simple example:
下面是一个简单的示例:
@Entity public class Employee{ public int id; public String name; public Employee boss; //more code follows }
When I load the Employee entity from the database the boss object is represented by a Hibernate proxy object, due to lazy loading. 当我从数据库加载Employee实体时,由于延迟加载,老板对象由Hibernate代理对象表示。 Later I need to access the boss property, which may or may not be in the same session it was loaded in. If I try to use the boss object and it hasn't been loaded and I am in a different seesion I will get the following error:
稍后,我需要访问boss属性,该属性可能在加载该会话的同一会话中,也可能不在同一会话中。如果我尝试使用boss对象并且尚未加载该对象,并且我的看法不同,我将获得以下错误:
Cause: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
How can I tell if the Employee entity the boss property is returning is a proxy or the actual entity? 如何确定老板属性返回的Employee实体是代理还是实际实体?
I really want an answer so I can do something like the following code: 我真的想要一个答案,所以我可以做类似下面的代码:
public Strin getBossName(Employee emp){ Employee boss; if(isProxy(emp){ boss = getBossFromDatabase(emp); }else{ boss = emp.getBoss(); }enter code here return boss.getName(); }
Thanks in advance! 提前致谢!
Hibernate在Hibernate
类中提供了这样的工具:
Hibernate.isInitialized(emp)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.