Querydsl,SELECT 中的子查询

问题描述 投票:0回答:2

我正在将以下 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

为了精确起见,我使用别名而不是 QType。

querydsl
2个回答
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 子句中执行子查询时通常根本效率不高。


-1
投票

如果您的正确查询是:

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();
© www.soinside.com 2019 - 2024. All rights reserved.