给定以下映射
<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>
如何包含或排除负载promotions
?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 的视图解析器),因此我自己实际上并不访问对象,因此任何尝试延迟加载集合结果在异常中(因为杰克逊将在所有集合属性上调用迭代器)。
这是一个显示将引发异常的示例:
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>
promotions
字段的数据类型是Collection<Promotion>
。