【问题标题】:Simplify the existing Hibernate Query Language (HQL)简化现有的 Hibernate 查询语言 (HQL)
【发布时间】:2018-02-27 01:27:04
【问题描述】:

我有一个需要简化的休眠查询,因为它有很多 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

如果有人能帮助我理解查询并简化它,我将不胜感激。非常感谢。

【问题讨论】:

  • JPQL 通常不需要任何 ON 子句,所以不知道为什么要添加这些子句。只有您知道实体和关系...如果您不使用 JPA,请删除 JPA 标签

标签: sql hibernate jpa hql


【解决方案1】:

您向我们显示的第一个查询是使用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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多