hibernate延迟加载代理对象实际对象读取方式

    public static <T>  T deproxy (T obj) {
if (obj == null)
return obj;
if (obj instanceof HibernateProxy) {
// Unwrap Proxy;
// -- loading, if necessary.
HibernateProxy proxy = (HibernateProxy) obj;
LazyInitializer li = proxy.getHibernateLazyInitializer();
return (T) li.getImplementation();
}
return obj;
}

所有解决的问题

当两个对象相互关联并使用懒加载时,从数据库中取出来使用时报错,通过调试查看对象所有字段的值为null;其中有个handle的对象,代表着为hibernater的缓存代理对象。但通过get\setXXX()有能得到该对象的字段值。但是 在不被get\setXXX()时获取原对象的类型时报错,提示 javax.persistence.EntityNotFoundException: Unable to find xxxxx

解决描述

在使用hibernate从数据库加载含有子类的实体类对象时,检查其真实类型是非常必要的。因为可能取出来的是一个代理对象。所以需要在取完数据之后判断该对象是否是其本身,是或不是就返回本身。

提供的一个工具类,如下:

public class HbUtils {

    public static <T>  T deproxy (T obj) {
if (obj == null)
return obj;
if (obj instanceof HibernateProxy) {
// Unwrap Proxy;
// -- loading, if necessary.
HibernateProxy proxy = (HibernateProxy) obj;
LazyInitializer li = proxy.getHibernateLazyInitializer();
return (T) li.getImplementation();
}
return obj;
} public static boolean isProxy (Object obj) {
if (obj instanceof HibernateProxy)
return true;
return false;
} // ---------------------------------------------------------------------------------- public static boolean isEqual (Object o1, Object o2) {
if (o1 == o2)
return true;
if (o1 == null || o2 == null)
return false;
Object d1 = deproxy(o1);
Object d2 = deproxy(o2);
if (d1 == d2 || d1.equals(d2))
return true;
return false;
} public static boolean notEqual (Object o1, Object o2) {
return ! isEqual( o1, o2);
} // ---------------------------------------------------------------------------------- public static boolean isSame (Object o1, Object o2) {
if (o1 == o2)
return true;
if (o1 == null || o2 == null)
return false;
Object d1 = deproxy(o1);
Object d2 = deproxy(o2);
if (d1 == d2)
return true;
return false;
} public static boolean notSame (Object o1, Object o2) {
return ! isSame( o1, o2);
} // ---------------------------------------------------------------------------------- public static Class getClassWithoutInitializingProxy (Object obj) {
if (obj instanceof HibernateProxy) {
HibernateProxy proxy = (HibernateProxy) obj;
LazyInitializer li = proxy.getHibernateLazyInitializer();
return li.getPersistentClass();
}
// Not a Proxy.
return obj.getClass();
} }
04-17 13:15
查看更多