gpt4 book ai didi

java - JPA 和 JPQL : NoResultException when selecting from multiple tables where one value is null

转载 作者:行者123 更新时间:2023-11-29 09:18:32 27 4
gpt4 key购买 nike

我正在使用 Java EE 6 并使用 JPA 的 javax.persistence.Entitymanager 查询数据库。我有一个 JPQL 查询代码片段,看起来像这样:

Query query = entityManager.createQuery("
select A.propertyX, B.propertyY, C.propertyZ
from TableA A, TableB B, TableC C
where A.id = :id and B.id = A.id and C.type = B.type
");
query.setParameter("id", id);
Object[] result = (Object[]) query.getSingleResult();

其中 propertyX/Y/X 都是对其他实体的引用。在我的例子中,来自 TableA、TableB 和 TableC 的匹配行都存在。对于匹配的行,TableA.propertyX 和 TableB.propertyY 保存值,而 TableC.propertyZ 为 null(并且不是必需的)。

我希望它执行并返回一个 Object[] 数组,其中前两个元素(propertyX 和 propertyY)的值为 null,第三个元素(propertyZ)为 null。

但是,当 propertyZ 为 null 时,将抛出 NoResultException。如果我更改数据以使 propertyZ 不为空,则查询将执行并返回一个值。

  • 这是预期的 JPQL 行为吗?
  • 如何确保我的查询按我最初预期的方式运行?

明显的解决方法是选择整个根实体而不是任何子属性,例如'C' 而不是 'C.propertyZ',然后从实体对象中获取属性。但是,我希望它在不这样做的情况下按我预期的那样工作。

最佳答案

如果对于 A 和 B 中的给定行,C 中有一行 C.type = B.type,但该行的 propertyZ 列为空,那么您的查询应该返回一条记录是对的.

但是,如果对于 A 和 B 中的给定行,在 C 中没有匹配的行,其中 C.type = B.type,那么您的查询将不会返回任何结果。这与JPQL无关,与SQL无关

如果你希望后一种情况仍然返回一条在propertyZ字段中为null的记录,你需要使用OUTER JOINs

HTH

关于java - JPA 和 JPQL : NoResultException when selecting from multiple tables where one value is null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8000247/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com