我对 Spring Data 相当陌生,我想创建一个查询,允许我在两个实体之间进行内部联接。
我一直在使用这个堆栈溢出来尝试澄清某些方面:
How To Define a JPA Repository Query with a Join
它给出了如下构造查询的答案:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
但是,在这个查询中,我看不到它在哪里设法定义“ar”,因为两个实体类实际上都没有在自身内部定义“ar”?对此的任何澄清将不胜感激!
最佳答案
考虑这个例子
SELECT c FROM Country c
这里,c称为范围变量。
Range variables are query identification variables that iterate over all the database objects of a specific entity class hierarchy (i.e. an entity class and all its descendant entity classes)
您可以阅读有关范围变量的更多信息 here
根据您的查询,没有“Area ar”,您需要了解此查询基于 JPQL(而不是 SQL)。考虑以下查询:
SELECT c1, c2 FROM Country c1 INNER JOIN c1.neighbors c2
JPQL 提供了称为连接变量的东西,它表示对指定对象集合的更有限的迭代。在上面的查询中,c1 是范围变量,而 c2 是绑定(bind)到路径 c1.neighbours 的连接变量,并且仅迭代该集合中的对象。
您可以在this article中阅读更多详细信息。
关于带连接的 Spring Data @Query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37549155/