【问题标题】:Jpql query across tablesjpql跨表查询
【发布时间】:2013-02-03 10:17:32
【问题描述】:

假设我有以下表格:

Table A: id b-id
Table B: id property

我可以在 JPQL 语言中像下面这样过滤表 A 的元素吗?

SELECT a FROM A a JOIN a.b-id targetId WHERE targetId.property = : someValue

我想获取表 A 的元素,其中引用的 B 元素具有 property = someValue

如果我介绍第三张桌子

Table A: id b-id
Table B: id c-id
Table C: id property

如何在 c.property=someValue 处获取 A 的元素?

我开始了解 ORM 的强大功能,但有些概念对我来说仍然很模糊。 谢谢你的回答

【问题讨论】:

    标签: jpa orm jpql


    【解决方案1】:

    JPQL 查询对实体而非数据库表进行操作。我假设实体和持久属性的名称与相关的表和数据库列的名称相匹配。

    因为所有有问题的关系都是单值、一对一或多对一的(每个A 只连接到一个B(或可能不连接到任何一个),每个B 都连接到一个C),根本不需要在查询中指定连接。

    SELECT a FROM A a WHERE a.b.c.property = someValue

    无需担心路径中的空值,因为正如 JPA 2.0 规范中所说:

    Path expression navigability is composed using “inner join” semantics. 
    That is, if the value of a non-terminal field in the path expression is null, 
    the path is considered to have no value, and does not participate in the 
    determination of the result.
    

    Same 不适用于集合值属性(一对多、多对多),因为无法通过路径表达式导航到它们的属性。

    【讨论】:

    • 这是一个非常准确的答案,谢谢!要将主题扩展到集合,您能否说明集合属性会发生什么?
    猜你喜欢
    • 1970-01-01
    • 2017-03-10
    • 2013-11-13
    • 2018-09-04
    • 2018-07-06
    • 2021-08-22
    • 2020-03-26
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多