2011-08-25 77 views
1

假设我有3个表格GrandCat,Cat和Kitt。他们有一对多的关系,所以我有以下类。所有关联都是延迟加载。休眠什么是加载对象图的正确方法

GrandCat{ 
    int age; 
    Set<Cat> cats; 
} 

Cat{ 
    int age; 
    Set<kitt> kitten; 
    GrandCat grandCat; 
} 

Kit{ 
    String color; 
    Cat cat; 
} 

我想建立一个grandCat的列表。条件是grandCat.age> 10和Cat.age> 5并且至少有一个颜色为黄色的kitt。当我做grandCat.getCats()时,只有猫满足条件返回。例如,我有以下猫。这样

grand 1(age>10)--> alex(age>5) ---> a(yellow),b,c    | 
       | 
       --> bob(age<5) --->d,e(yellow) 

grand 2(age>10) --> charlie(age<5) ---> f,g(yellow) 
        | 
        --> david(age>5)--->h 
        | 
        -->edward(age>5)-->j(yellow) 
        | 
        -->fay(age>5) --> i(yellow),k(yellow) 

other grandCats........ 

我想有回报GrandCats 关系是盛大1个grand2这样

grand1-->alex-->a 
    grand2-->edward-->j 
      | 
      -->fay-->i,k 

他们grandcat,猫,小猫的millons,所以不希望加载他们然后过滤。

我知道我可以通过使用

select g,c,k from grandCat g inner join fetch g.cat c inner join fetch c.kitten k where g.age>10 and c.age>5 and k.color='yellow'. 

,然后循环返回值,看看哪些猫实现它属于哪个grandCat和小猫猫。但这有一些缺点,在grandcat和cat级别上有重复。因为他们返回为

grand1-->alex-->a 
    grand2-->edward-->j 
    grand2-->fay-->i   
    grand2-->fay-->k 

所以我需要比较他们和过滤器,当有很多记录时,这需要时间和消耗资源。 任何人都有一个很好的方式来加载?我应该使用3 hql吗?首先得到匹配grandCat1和grand2

select g from grandCat g inner join fetch g.cat c inner join fetch c.kitten k where g.age>10 and c.age>5 and k.color='yellow'. 

然后用从去年的查询grandcat返回查询的猫,然后把猫grand.setcats()

select c from Cat c inner join fetch cat.grandCat g inner join fetch c.kitten k where g=:grandCat and c.age>5 and k.color='yellow' 

然后查询小猫,做同样的事情?

select k from Kitt k inner join fetch k.cat c where c=:cat and k.color='yellow' 

它似乎很单调。

这样做的最好方法是什么?顺便说一下,我希望返回的grandCat及其“猫和小猫”仍然具有延迟加载能力,比如说小猫有其他关联,我可以稍后通过延迟加载来使用它们。

回答

0
select distinct g from GrandCat g 
inner join fetch g.cat c 
inner join fetch c.kitten k 
where g.age>10 
and c.age>5 
and k.color='yellow' 

应该很好。返回的Grandcat只会在其猫集合中包含想要的猫,并且每只猫只会在其小猫集合中拥有想要的小猫。

请注意,虽然Hibernate返回实体,但这些实体并不反映关联的实际情况。我会将它们视为只读对象,而不是试图以任何方式修改关联,因为它可能会产生灾难性的副作用。

+0

我相信这会返回满意的grandCats,但是当你做grandcat.getCats()时,所有来自这个grandcat的猫都会返回,无论它小于5岁,并且没有任何黄色的kitt – Nan

+0

为什么你不尝试一下? –

+0

我前几天问过这个问题,真的做了测试。 http://stackoverflow.com/questions/7164606/hibernate-hql-how-to-get-matched-child-from-parent – Nan

相关问题