2012-03-16 74 views
5

我想知道是否有可能有一個@Query註釋子查詢(org.springframework.data.jpa.repository.Query;)SpringData:有可能在查詢註釋中有子查詢嗎?

我得到第一個子查詢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") 

謝謝!

+1

這不是關於Spring Data,我相信你也不能在JPQL中做到這一點。 – 2012-03-16 19:49:46

回答

6

不,在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) 
0

@Query註釋的內容被或多或少地傳遞通過調用EntityManager.createQuery(…)來提供給持久性提供者。所以在@Query中可以使用哪些內容。 AFAIK,JPQL(到JPA 2.0時)僅支持子查詢EXISTSIN子句。

+0

JPA 2.0支持WHERE和HAVING子句中的子查詢。在那些他們可以用於許多類型的表達式,包括EXISTS和IN。 – 2012-05-01 17:12:53

1

我沒有得到在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); 

其中

Table2Obj & Table3Obj分別實體Table 1和表2,表3之間的關係的映射。

定義如下。

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