Hibernate获取具有多个关联

时间:2013-01-14 21:36:55

标签: java spring hibernate

我正在为实体对象上的延迟加载集合执行此操作:

@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();
    }

1 个答案:

答案 0 :(得分:3)

docs包含以下内容:

List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "Fritz%") )
    .setFetchMode("mate", FetchMode.EAGER)
    .setFetchMode("kittens", FetchMode.EAGER)
    .list();
  

此查询将通过外部联接获取配偶和小猫。有关更多信息,请参见第20.1节“获取策略”。