简化现有的Hibernate查询语言(HQL)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简化现有的Hibernate查询语言(HQL)相关的知识,希望对你有一定的参考价值。
我有一个hibernate查询,我需要简化,因为它有很多joins
。我觉得在某些情况下连接是不必要的。我试图理解并简化查询以在执行后获得相同的结果。但是,我无法这样做。这是查询:
Select a from Animal a
left join Cat on cat.id = animal.id
left join Dog as dog on cat.id = dog.id
left join Wolf on animal.id = wolf.id
left join Monkey on animal.id = monkey.id
left join Location as location on cat.location.id = location.id
left join LocationZone as zone on zone.id = location.locationZone.id
left join Place as place on place.id = monkey.place.id
left join Location as newLocation on place.location.id =newLocation.location.id
left join LocationZone as newZone on newZone.id = newLocation.LocationZone.id
WHERE ((cat.location.id is null and monkey.place.id is null)
OR newLocation.locationZone.id = 1 or zone.locationZone.id = 1;
这是我尝试过的东西:
Select a from Animal a where Type(a) in (Cat, Dog, Wolf, Monkey) and (a.location.id is null and a.place.id is null) or (a.location.locationZone.id = 1 or a.place.location.locationZone.id = 1);
但是,我得到空的结果。我无法理解上面的查询试图实现什么,但我需要简化查询,因为有很多连接。那么,这是基本信息:
- Cat, Dog, Wolf, Monkey extends Animal
- Cat has location
- Location has locationZone
- Monkey has place
- Place has locaiton
如果有人能帮助我理解查询并简化查询,我将非常感激。非常感谢你。
答案
您向我们展示的第一个查询是使用JOIN
,如果您在实体中映射关系,那么这是不必要的。
因此,想象您映射查询中显示的每个实体之间的关系,简化的JPQL查询可以是:
Select a from Animal a
LEFT JOIN animal.cat cat
LEFT JOIN animal.dog
LEFT JOIN animal.wolf wolf
LEFT JOIN animal.monkey monkey
LEFT JOIN cat.location catLocation
LEFT JOIN catLocation.locationZone catLocationZone
LEFT JOIN monkey.place monkeyPlace
LEFT JOIN monkeyPlace.location monkeyLocation
LEFT JOIN monkeyLocation.locationZone monkeyLocationZone
LEFT JOIN monkeyLocation.location newMonkeyLocation
LEFT JOIN newMonkeyLocation.locationZone newMonkeyLocationZone
WHERE ((catLocation.id is null and monkeyPlace.id is null)
OR monkeyLocationZone.id = 1 or newMonkeyLocationZone.id = 1;
以上是关于简化现有的Hibernate查询语言(HQL)的主要内容,如果未能解决你的问题,请参考以下文章