如何将这个SQL查询转换为Hibernate的HQL?

时间:2017-02-03 09:47:11

标签: java mysql hibernate hql

之前使用过Hibernate但从未达到过这种程度,我在尝试将以下查询转换为有效的Hibernate SQL查询时遇到了困难。

SELECT * FROM
(SELECT * FROM scripts WHERE (script.type LIKE 'DATA'))
AS A JOIN
(SELECT * FROM req_executions  
WHERE (req_executions.fk_database NOT IN 
(SELECT executions.fk_database FROM executions
WHERE executions.fk_script = req_executions.fk_script))
OR ((req_executions.fk_database = 12 AND req_executions.fk_database != 8) 
AND req_execution.fk_database NOT IN (SELECT executions.fk_database FROM execution
WHERE executions.fk_script = req_executions.fk_script)))
AS B
ON (A.id = B.fk_script)

此查询的结果是一个过滤的待执行脚本表。 我尝试过这样的事情:

"SELECT req FROM (SELECT s FROM Script s  
WHERE( s.filename LIKE :filename AND s.type = :scriptType AND s.ticketNumber LIKE :ticketNumber ) 
JOIN (SELECT re FROM RequiredExecution re 
WHERE (re.key.databaseId NOT IN (SELECT e.database FROM Execution e WHERE e.script.id = re.key.scriptId))
OR ((re.key.databaseId = :forAllId AND :dbId != :syncId)
AND re.key.databaseId NOT IN
(SELECT e.database FROM Execution e WHERE e.script.id = re.key.scriptId)))) WHERE (s.id = re.key.scriptId)"

并使用“AS” 但我还远没有解决方案。有什么提示吗?

2 个答案:

答案 0 :(得分:0)

我认为你必须从实体中选择而不是从另一个SELECT中选择...我不知道是否可能,反正似乎很难。

您可能会考虑使用本机SQL查询调用session.createSQLQuery("the native SQL")。 并.addEntity(YourEntityClass.class)自动映射结果 和.setParameter(,0基于编号,而查询使用?占位符而不是:named_pa​​rameter。

答案 1 :(得分:0)

最后我被迫使用nativeQuery,因为" ... HQL子查询只能出现在select或where子句中。"如14.13. Subqueries中所述。