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(); } }