如何取消代理休眠对象 [英] how to unproxy a hibernate object

查看:18
本文介绍了如何取消代理休眠对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何取消代理休眠对象,以便支持多态?

How can I unproxy a hibernate object, such that polymorphism would be supported?

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

Consider the following example. Classes A and B are two hibernate entities. B has two subtypes C and 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
        }
    }
}

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

This code fails to execute either the C or D block, since the B collection has been lazy loaded, and all instances of B are Hibernate proxies. I'd like a way to unproxy each instance.

注意:我意识到可以优化查询以急切地获取所有 B.我正在寻找替代方案.

Note: I realize the query can be optimized to eagerly fetch all B's. I'm looking for an alternative.

推荐答案

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

Here's our solution, added to our persistence utils:

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

这篇关于如何取消代理休眠对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆