在HQL上选择内连接

我想用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解决方案方法:

需要先import:

 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" ); 

更多关于此链接
和HERE(加入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的人来说)。

您无法使用on关键字定义联接。 Hibernate知道如何根据您的映射进行连接。 如果在a和b之间的映射中定义关系,则hibernate将根据您定义的关系进行连接。 如果你有a和b之间的关系而不是内连接而不使用on并将连接标准放在where子句中