编程语言
首页 > 编程语言> > java – 如何有条件地加载映射在对象中的集合?

java – 如何有条件地加载映射在对象中的集合?

作者:互联网

给出以下映射

<class name="com.domain.Season" table="cm.pub.jsn_mstr">
    <id name="seasonCode" column="season_code" length="1"/>
    <property name="name" type="string" column="name" length="20"/>
    <set name="promotions" lazy="false">
        <key column="season_code"/>
        <one-to-many class="com.domain.Promotion" not-found="ignore"/>
    </set>
</class>

如何包含或排除促销活动?我可以使用lazy =“true”虽然我使用Jackson来序列化会话结束后的结果.

public Collection<Season> getSeasons(boolean withPromotions) {
    final Session session = sessionFactory.getCurrentSession();
    try {
        session.beginTransaction();
        return (List<Season>) session.createQuery("from Season s").list();
    } finally {
        session.getTransaction().commit();
    }
}

更新:使用延迟加载的问题.

上面的getSeasons方法用于将检索季节的MVC控制器,然后使用jackson将它们序列化为JSON(使用Spring / MVC的视图解析器),因此我实际上并不自己访问这些对象,因此任何延迟加载集合的尝试导致异常(因为jackson将在所有集合属性上调用迭代器).

这是一个示例,显示将抛出异常:

public Collection<Season> getSeasons(boolean withPromotions) {
    final Session session = sessionFactory.getCurrentSession();
    final List<Season> r;
    try {
        session.beginTransaction();
        r = (List<Season>) session.createQuery(
                withPromotions
                ? "from Season s join fetch s.promotions"
                : "from Season s"
                ).list();
    } finally {
        session.getTransaction().commit();
    }
    try {
        for (Season s : r) {
            for (Promotion p : s.getPromotions()) {
                // Exception thrown here as we attempted to get an iterator.
                LOG.debug("Promotion: " + p.getName());
            }
        }
    } catch (Exception ex) {
        LOG.error("Couldn't get promotions", ex);
    }
    return r;
}

当然,这次映射需要lazy =“true”,否则它总是渴望阅读集合.

<class name="com.domain.Season" table="cm.pub.jsn_mstr">
    <id name="seasonCode" column="jsn_seas" length="1"/>
    <set name="promotions" lazy="true">
        <key column="jpr_seas"/>
        <one-to-many class="com.domain.Promotion" not-found="ignore"/>
    </set>
</class>

促销字段的数据类型是Collection< Promotion>.

解决方法:

试试这个:

session.createQuery("from Season s join fetch s.promotions").list();

从hibernate参考:
“fetch”连接允许使用单个select来初始化值的关联或集合及其父对象.

标签:java,hibernate,hibernate-4-x
来源: https://codeday.me/bug/20190902/1790955.html