Hibernate:LazyLoading - 在一对多集合中按对象搜索

时间:2012-11-02 06:18:16

标签: performance hibernate join associations one-to-many

我有一个实体1 - > SubEntity n One-To-Many-relation。

我只是想检查,如果这是最有效的方式来搜索实体,包括其“一对多收集”中的指定SubEntity 。它可以工作,但如果我不需要加载所有SubEntities,我是否必须加入获取SubEntities或是否有更轻量级解决方案? (FetchMode = Lazy)

public Entity getEntityBySubEntity(SubEntity subEntity) { 
     List<Entity> result = (List<Entity>)getHibernateTemplate.findByNamedParam(
         "From Entity as e left join fetch e.subEntities as sub where sub.id = :id","id",subEntity.getId()); 
     if (!result.isEmpty()) { 
          return result.get(0);
     } else {
          throw new NoResultException();
     }
 }

(顺便说一下,应该只有一个结果......)

在adv中,

cav

1 个答案:

答案 0 :(得分:0)

您的查询很好,但不必要地获取子实体。只需删除fetch关键字即可。并且由于子实体不能为空以满足条件,因此内连接是正确的:

select e from Entity e inner join e.subEntities sub where sub.id = :id