Java SpringData:在查询注释中可以有子查询吗?

Java SpringData:在查询注释中可以有子查询吗?,java,jpql,spring-data,Java,Jpql,Spring Data,我想知道是否可以在@Query annotation org.springframework.data.jpa.repository.Query中有子查询 我在第一个子查询parentesis上得到一个QuerySyntaxException 这是我的问题 @Query(value="select c1 from ComplaintModel c1, " + "(select c2.id, min(cb.termDate) minDate from ComplaintModel c2 " + "

我想知道是否可以在@Query annotation org.springframework.data.jpa.repository.Query中有子查询

我在第一个子查询parentesis上得到一个QuerySyntaxException

这是我的问题

@Query(value="select c1 from ComplaintModel c1, "
+ "(select c2.id, min(cb.termDate) minDate from ComplaintModel c2 "
+ "join c2.complaintBullets cb join cb.status s where s.code = ?1 "
+ "group by c2.id) tmp where c1.id = tmp.id order by tmp.minDate")

谢谢

否,在JPQL查询中的select子句中不可能有子查询

JPQL支持WHERE和HAVING子句中的子查询。它至少可以是任意、某些、全部、IN、EXIST表达式的一部分,当然也可以用于普通条件表达式:

SELECT a
FROM A a
WHERE a.val = (SELECT b.someval 
               FROM B b 
               WHERE b.someotherval=3)

@Query注释的内容通过调用EntityManager.createQuery…或多或少地传递给持久性提供程序…。因此,在@Query中可以使用其中允许的任何内容。AFAIK,JPA2.0时代的JPQL只支持EXISTS和IN子句的子查询。

我确实在Spring数据JPA中获得了预期的结果

public final static String FIND_BY_ID_STATE = "SELECT a FROM Table1 a RIGHT JOIN a.table2Obj b " +
                                              "WHERE b.column = :id" +
                                              "AND a.id NOT IN (SELECT c.columnFromA from a.table3Obj c where state = :state)";


@Query(FIND_BY_ID_STATE)
public List<Alert> findXXXXXXXX(@Param("id") Long id, @Param("state") Long state);
在哪里

表2obj和表3obj分别是实体表1和表2、表3之间关系的映射

定义如下

@OneToMany(mappedBy = "xxx", fetch = FetchType.LAZY)
private Set<Table2> table2Obj = new HashSet<>();

这与Spring数据无关,我相信在JPQL中也不能这样做。JPA2.0支持WHERE和HAVING子句中的子查询。在这些表达式中,它们可以用在许多类型的表达式中,包括EXISTS和In。