简体   繁体   English

Spring-Data-Jpa:带有子查询的 INNER JOIN

[英]Spring-Data-Jpa: INNER JOIN with Subquery


I have the following problem.我有以下问题。 I want to execute this query in my spring boot project.我想在我的 Spring Boot 项目中执行这个查询。 I tried to do this with the query annotation in the JPA repository interface.我尝试使用 JPA 存储库界面中的查询注释来做到这一点。 But it says "unexpected SELECT" at the inner join.但是它在内部联接中说“意外的选择”。 When I execute this query directly on my mySQL database, it will work.当我直接在 mySQL 数据库上执行此查询时,它将起作用。

Do anyone have a solution for this case?有没有人对这种情况有解决方案?

This is my query:这是我的查询:

SELECT t1.*
FROM az_manager t1
INNER JOIN
(
    SELECT maID, MAX(datum) AS max_date
    FROM az_manager
    WHERE maID IN (7243, 1)
    GROUP BY maID
) t2
   ON t1.maID = t2.maID AND t1.datum = t2.max_date
WHERE
    t1.maID IN (7243, 1);

This is my class:这是我的课:

@Entity
@Table(name = "az_manager")
@IdClass(TnsWorkingHoursManagerId.class)
@Getter
@Setter
public class TnsWorkingHoursManager extends TnsObject{

    @Id
    @Column(name = "datum")
    private long date;

    @Id
    @Column(name = "maid")
    private int employeeId;

    @Column(name = "typid")
    private int typeId;

    @Column(name = "bemerkung")
    private String comment;

    @Column(name = "host")
    private String host;

    @Column(name = "modus")
    private byte mode;

    public TnsWorkingHoursManager() {
    }

}

Here is my try with the JPA repository:这是我对 JPA 存储库的尝试:

@Query(value = "SELECT azm1 FROM az_manager azm1 INNER JOIN (SELECT maID, MAX(datum) AS max_date FROM az_manager WHERE maID IN(:userIds) GROUP BY maID) azm2 ON azm1.maID = azm2.maID AND azm1.datum = azm2.max_date WHERE azm1.maID IN (:userIds)")
    List<TnsWorkingHoursManager> getLastEntries(@Param("userIds") ArrayList<Integer> userIds);

At the second select it says "'SELECT' unexpected"在第二个选择它说“'SELECT'意外”

For anyone else that might stumble upon this question:对于可能偶然发现这个问题的其他人:

If you don't add the nativeQuery = true parameter to the @Query annotation in a Spring Repository, the query will be considered as written in JPQL.如果没有在 Spring Repository 中的@Query注解中添加nativeQuery = true参数,则查询将被认为是用 JPQL 编写的。

From the JPQL docs :来自 JPQL 文档

Subqueries may be used in the WHERE or HAVING clause.子查询可以用在 WHERE 或 HAVING 子句中。

Based on the quote above, the JPQL (Java Persistence Query Language) does not support subqueries in the FROM clause and that is why OP had to make the query native in order for it to work.根据上面的引用,JPQL(Java 持久性查询语言)不支持 FROM 子句中的子查询,这就是为什么 OP 必须使查询本地化才能使其工作。

I have found a solution.我找到了解决办法。 I forgot to add ", nativeQuery = true" at the end of the line, but in the bracket.我忘了在行尾添加“, nativeQuery = true”,但在括号中。 Now it works.现在它起作用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM