0

我有一个实体 1 -> 子实体 n 一对多关系。

我只是想检查一下,这是否是搜索实体的最有效方式,包括其 "One-To-Many-Collection" 中的指定子实体。它有效,但是如果我不需要加载所有子实体,我是否必须加入获取子实体或者是否有更轻量级的解决方案?(FetchMode = 懒惰)

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

(顺便说一句,应该总是只有一个结果......)

thx in adv,

骑士

4

1 回答 1

0

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

select e from Entity e inner join e.subEntities sub where sub.id = :id
于 2012-11-02T07:33:23.343 回答