SELECT中的Querydsl,子查询

时间:2016-05-13 16:09:54

标签: querydsl

我正在运行以下SQL作为本机查询,但我想知道是否有办法在JPAQuery中运行它以便使用元组或类实例化。

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

为了精确,我使用别名而不是QTypes。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

我不认为JPQL和JPA支持select子句中的子查询:

JPQL LangRef:https://docs.oracle.com/html/E13946_04/ejb3_langref.html#ejb3_langref_select_clause

The SELECT clause has the following syntax:

select_clause ::= SELECT [DISTINCT] select_expression {, select_expression}*

select_expression ::= single_valued_path_expression | aggregate_expression | 
identification_variable | OBJECT(identification_variable) | constructor_expression

constructor_expression ::= NEW constructor_name ( constructor_item {, 
constructor_item}* )

constructor_item ::= single_valued_path_expression | aggregate_expression

aggregate_expression ::= { AVG | MAX | MIN | SUM } ([DISTINCT] 
state_field_path_expression) | COUNT ([DISTINCT] identification_variable | 
state_field_path_expression | single_valued_association_path_expression)

作为一种解决方法,您可以在视图顶部执行本机查询或实体。为了使事物保持合理的清洁状态,您可以创建仅包含子查询(和主键)的视图,并在实体之间进行懒惰的一对一映射。

请注意,(复杂的)谓词可能无法有效地推入视图查询中,并且在select子句中进行子查询时通常通常效率不高。