我想要做这样的事情与HQL:
SELECT *
FROM tableA a
INNER JOIN (select fieldA, sum(fieldB) as sum from tableB) b
ON a.fieldA = b.fieldA and a.fieldC = b.sum;
但是,这给出了一个错误:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: (...
有没有办法让这个使用HQL和Hibernate?
尝试本地SQL解决办法:
需要toimport这首:
import org.hibernate.SQLQuery;
然后在某处你的代码:
SQLQuery query = session.createSQLQuery(
"SELECT * FROM tableA a
INNER JOIN
(SELECT fieldA, sum(fieldB) as sum from tableB) b
ON a.fieldA = b.fieldA and a.fieldC = b.sum"
);
更多此链接
和这里(在Hibernate查询语言连接)
你可以尝试做这样的事与HQL:
String sqlText =
"select entityA
from EntityA entityA, EntityB entityB
where entityA.fieldA=entityB.fieldA
and entityA.fieldC=(select sum(entityB.fieldB)
from EntityB entityB
where entityB.fieldA=entityA.fieldA)"
Query query = session.createQuery(sqlText);
它应该类似于您的SQL。 关于你的说法 - 因为我知道你不能使用HQL内视图,因为它是面向对象的。
这里是一个很好的文章关于加入中HQL。
编辑:
据user1495181笔记上面的查询可以写成像(但我不知道):
String sqlText =
"select entityA
from EntityA entityA
join entityA.entitiesB entityB
Where entityA.fieldC=(select sum(entityB.fieldB)
from EntityB entityB
where entityB.fieldA=entityA.fieldA)"
但我更喜欢第一个变体因为对我来说更容易理解(特别是对谁使用本地SQL合作人)。
您不能定义与关键字的加入。 休眠知道如何根据你的映射公司携手进行。 如果你定义A和B之间的映射不是休眠的关系会做联接基础上的关系,你定义。 如果你有A和B不是做内部联接,而无需使用上,并把连接标准的where子句中的关系