对于(如你所说),我使用'deproxy()'和一些其他的辅助函数,某些类型的代码。
这使得Spring'autogrow'路径绑定工作,在通过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();
}
}
我在每个主要的Hibernate项目中都使用这样的类。 PS:这不是我唯一的Hibernate帮助器 - 我有一个用于一般地获取ID并检查实体是新/存在的。
希望这会有所帮助!
我已经测试过它并且完美地工作。非常感谢你,这让我失去了很多时间! – droidpl 2013-05-05 11:05:54
不客气! – 2013-05-05 11:20:50
这个util对我很有帮助。非常感谢你 – 2016-01-15 02:55:58