【问题标题】:How to know if the Child Entity is loaded or not in the Parent Entity in hibernate如何知道子实体是否在休眠中的父实体中加载
【发布时间】:2015-07-28 11:39:16
【问题描述】:

我有一个带有fetch=FetchType.LAZY 关系映射的休眠实体

喜欢:

....
private ConsumerEntity consumerEntity;

@ManyToOne(fetchType.LAZY)
@JoinColumn(name="orderId", insertable=false, updateable=false)
public ConsumerEntity getConsumerEntity(){
    return this.consumerEntity;
}
....

我想将实体对象转移到HashMap<String, Object>,我使用Introspector 执行此操作,目前只是忽略子实体,只将非实体成员解析到地图:

protected Map<String, Object> transBean2Map(Object beanObj){
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(beanObj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();

                if (!key.equals("class")
                       && !key.endsWith("Entity")) {
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(beanObj);
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            Logger.getAnonymousLogger().log(Level.SEVERE,"transBean2Map Error " + e);
        }
        return map;
    }

我想将地图中的每个子实体作为嵌入地图,仅当它们已被获取(可能通过显式调用 getter() 方法或意外 通过其他方法加载,在不打扰的时候提供奖励信息总是一个好主意,对吧?)。

不,我不想把所有东西都写成fetchType.EAGER。只想检测子实体是否已经加载,然后将它们传输并嵌入到父 Map,否则,什么都不做(不会查询数据库来获取它)。

进行嵌入不会很麻烦,也许只是一些递归。所以我需要知道子实体是否已经加载到父实体中,就像上面示例中的 consumerEntity 一样。

有什么办法可以做到吗?

【问题讨论】:

    标签: java hibernate lazy-loading


    【解决方案1】:

    Hibernate 为此提供了一些工具,您可以尝试以下方法

    if (HibernateProxy.class.isInstance(entity.getConsumerEntity())) {
        HibernateProxy proxy = HibernateProxy.class.cast(entity.getConsumerEntity());
        if (proxy.getHibernateLazyInitializer().isUninitialized()) {
            // getConsumerEntity() IS NOT initialized
        } else {
            // getConsumerEntity() IS initialized
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      相关资源
      最近更新 更多