如何unproxy一个hibernate对象

Pet*_*ton 8 java hibernate

如何解析hibernate对象,以便支持多态?

请考虑以下示例.类A和B是两个休眠实体.B有两个亚型C和D.

List<A> resultSet = executeSomeHibernateQuery();
for(A nextA : resultSet) {
    for(B nextB : nextA.getBAssociations() {
        if(nextB instanceof C) {
            // do something for C
        } else if (nextB instanceof D) {
            // do something for D
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码无法执行C或D块,因为B集合已延迟加载,并且B的所有实例都是Hibernate代理.我想要一种解开每个实例的方法.

注意:我意识到可以优化查询以急切地获取所有B.我正在寻找另一种选择.

Pet*_*ton 18

这是我们的解决方案,添加到我们的持久性工具中:

public T unproxy(T proxied)
{
    T entity = proxied;
    if (entity instanceof HibernateProxy) {
        Hibernate.initialize(entity);
        entity = (T) ((HibernateProxy) entity)
                  .getHibernateLazyInitializer()
                  .getImplementation();
    }
    return entity;
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您不需要检查实体是否为空(请参阅 http://stackoverflow.com/questions/2950319/is-null-check-needed-before-calling-instanceof) (2认同)

Rad*_*icz 12

现在 Hibernate 有专门的方法:org.hibernate.Hibernate#unproxy(java.lang.Object)

  • `YourEntity unproxiedEntity = (YourEntity) Hibernate.unproxy(yourEntity);` (4认同)