Spring Data @Query 与连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37549155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:05:59  来源:igfitidea点击:

Spring Data @Query with Joins

springjoinspring-dataspring-data-jpa

提问by James Millner

I am fairly new to Spring Data and I want to create a query that will allow me to do an Inner Join between two entities.

我对 Spring Data 相当陌生,我想创建一个查询,允许我在两个实体之间进行内部联接。

I have been using this stack overflow to try to clarify certain aspects:

我一直在使用这个堆栈溢出来试图澄清某些方面:

How To Define a JPA Repository Query with a Join

如何使用联接定义 JPA 存储库查询

It gives the answer of structuring the query as so:

它给出了构造查询的答案,如下所示:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

However in this query I dont see where it manages to define "ar" as neither of the entity classes actually define "ar" within themselves? Any clarification on this would be greatly appreciated!

但是在这个查询中,我没有看到它在哪里设法定义“ar”,因为实体类实际上都没有在它们内部定义“ar”?对此的任何澄清将不胜感激!

回答by koder23

Consider this example

考虑这个例子

SELECT c FROM Country c

Here, c is called a range variable.

这里,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)

范围变量是查询标识变量,它遍历特定​​实体类层次结构(即实体类及其所有后代实体类)的所有数据库对象

You can read more about range variables here

您可以在此处阅读有关范围变量的更多信息

As per your query that there is no "Area ar"you need to understand that this query is based on JPQL (not SQL). Consider the below query:

根据您的查询,没有“区域 ar”,您需要了解此查询基于 JPQL(而非 SQL)。考虑以下查询:

SELECT c1, c2 FROM Country c1 INNER JOIN c1.neighbors c2

JPQL provides something called as a join variable, which represent a more limited iteration over specified collections of objects. In the above query, c1 is a range variable while c2 is a join variable that is bound to the path c1.neighbours and iterates only over objects in that collection.

JPQL 提供了一种称为连接变量的东西,它表示对指定对象集合的更有限的迭代。在上面的查询中,c1 是一个范围变量,而 c2 是一个连接变量,它绑定到路径 c1.neighbors 并且只迭代该集合中的对象。

You can read about it in more detail in this article

您可以在本文中更详细地了解它

回答by Ibrahim Khalil

area is actually defined in User entity class and in your query area is aliased with "ar" and used as second entity of the join.

区域实际上是在 User 实体类中定义的,在您的查询区域中,别名为“ar”并用作连接的第二个实体。

@Query("select u.userName from User u inner join **u.area** ar
        where ar.idArea = :idArea")