2016-05-13 198 views
4

我正在運行以下SQL作爲本機查詢,但我想知道是否有方法在JPAQuery中運行它以便使用元組或類實例化。Querydsl,SELECT中的子查詢

SELECT a.*, 
     (SELECT exists (SELECT 1 FROM Table b WHERE b.a_code = a.code AND b.other = ?)) AS bloquant 
FROM Table a 

爲了精確,我使用別名而不是QTypes。

+0

你的意思是:'選擇一個* FROM tableA的 其中存在( SELECT 1 FROM tableb b WHERE b.a_code = a.b_code AND b.other =?)'可以寫成'select a。* from table_a a where a_code in(從tableb b中選擇b.a_code,其中a.a_code = b.a_code和其他=?)' – KarlP

回答

0

如果你正確的查詢是:

SELECT * 
FROM tablea 
WHERE EXISTS(SELECT 1 FROM tableb WHERE tableb.a_code=tablea.code and tableb=$PARAM_VALUE); 

然後你就可以得到正確的SQL表達式這樣做:

QTableA qTableA = new QTableA("tablea"); 
QTableB qTableB = new QTableB("tableb"); 

// Subquery creation 
SQLQuery subquery = SQLExpressions.selectOne() 
    .from(qTableB) 
    .where(qTableB.a_code.eq(qTableA.code).and(qTableB.other.eq(PARAM_VALUE))); 
return subquery.exists(); 

SQLQuery query = new SQLQuery(); 
query.setUseLiterals(true); 
query 
    .select(SQLExpressions.countAll) 
    .from(qTableA) 
    .where(subquery.exists()); 
return query.getSQL().getSQL();