我这样做是为了对实体对象进行延迟加载:
@Transactional(readOnly = true)
public T getWithAssociation(final long id,String association) {
Session session = sessionFactory.getCurrentSession();
final Criteria crit = session.createCriteria(genericType);
crit.setFetchMode(association,FetchMode.JOIN);
crit.add(Property.forName("id").eq(id));
return (T) crit.uniqueResult();
}
我想返回一个已加载多个延迟加载的集合的实体对象,我可以这样做吗(传递一个列表并为单个条件设置比关联更多的值?):
@Transactional(readOnly = true)
public T getWithAssociations(final long id,List<String> associations) {
Session session = sessionFactory.getCurrentSession();
final Criteria crit = session.createCriteria(genericType);
for(String association:associations) {
crit.setFetchMode(association,FetchMode.JOIN);
}
crit.add(Property.forName("id").eq(id));
return (T) crit.uniqueResult();
}
最佳答案
是?
List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("name","Fritz%") )
.setFetchMode("mate",FetchMode.EAGER)
.setFetchMode("kittens",FetchMode.EAGER)
.list();
This query will fetch both mate and kittens by outer join. See Section 20.1,“Fetching strategies” for more information.