SpringData : is it possible to have subqueries in the Query annotation?

前端 未结 3 1763
庸人自扰
庸人自扰 2020-12-06 11:48

I would like to know if it is possible to have subquery in a @Query annotation (org.springframework.data.jpa.repository.Query;)

I am getting a QuerySyntaxException o

相关标签:
3条回答
  • 2020-12-06 12:19

    The content of the @Query annotation is more or less passed as is to the persistence provider by calling EntityManager.createQuery(…). So whatever is allowed in there can be used in @Query. AFAIK, JPQL (by the time of JPA 2.0) only supports subqueries for EXISTS and IN clauses.

    0 讨论(0)
  • 2020-12-06 12:33

    No, it is not possible to have subquery in the select clause in JPQL query.

    JPQL supports subqueries in WHERE and HAVING clauses. It can be (at least) part of ANY, SOME, ALL, IN, EXIST expressions, and of course it can be used normal conditional expressions:

    SELECT a
    FROM A a
    WHERE a.val = (SELECT b.someval 
                   FROM B b 
                   WHERE b.someotherval=3)
    
    0 讨论(0)
  • 2020-12-06 12:40

    I did get expected results in Spring-data jpa with

    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);
    

    where

    Table2Obj & Table3Obj are the mapping of the relationship between entities Table1 and Table2, Table3 respectively.

    defined Like below.

    @OneToMany(mappedBy = "xxx", fetch = FetchType.LAZY)
    private Set<Table2> table2Obj = new HashSet<>();
    
    0 讨论(0)
提交回复
热议问题