java-具有多个关联的休眠获取

前端之家收集整理的这篇文章主要介绍了java-具有多个关联的休眠获取 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我这样做是为了对实体对象进行延迟加载:

@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();
    }
最佳答案
是?

docs包含以下内容

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.

猜你在找的Spring相关文章