我有一个令人讨厌的查询,它连接了三个不同的查询。我认为没有任何Hibernate方法来处理联合(我们使用Hibernate 3.0.5),因此该语句被编写为SQLQuery。
我们需要单个语句而不是使用3个单独的HQL语句,以便我们可以使用Hibernate Criteria setFirstResult和setMaxResults方法。
不需要仅选择某些字段,因此选择f。*等会更好(如果这样可以更容易)(尽管我必须对每列进行别名以避免重复的列名称。)
SELECT * FROM (
SELECT f.id as foo_id,
f.name as foo_name,
NVL(b2.name, ' ') as baz_name,
NVL(b1.name, ' ') as bar_name,
NVL(b1.alias, ' ') as bar_alias,
NVL(b1.description, ' ') as bar_description
FROM foo f
LEFT JOIN bar b1 ON f.id = b1.foo_id
LEFT JOIN baz b2 ON f.id = b2.foo_id AND b1.baz_id = b2.id
UNION
SELECT f.id as foo_id,
f.name as foo_name,
NVL(b2.name, ' ') as baz_name,
NVL(b1.name, ' ') as bar_name,
NVL(b1.alias, ' ') as bar_alias,
NVL(b1.description, ' ') as bar_description
FROM foo f
LEFT JOIN baz b2 ON f.id = b2.foo_id
LEFT JOIN bar b1 ON b2.id = b1.baz_id
WHERE b1.id IN (select b1b.id from bar b1b where b1b.foo_id = f.id)
UNION
SELECT f.id as foo_id,
f.name as foo_name,
NVL(b2.name, ' ') as baz_name,
NVL(b1.name, ' ') as bar_name,
NVL(b1.alias, ' ') as bar_alias,
NVL(b1.description, ' ') as bar_description
FROM foo f
LEFT JOIN baz b2 ON f.id = b2.foo_id
LEFT JOIN bar b1 ON b2.id = b1.baz_id
WHERE b2.id IN (select b22.id from baz b22 where b22.foo_id = f.id)
);
答案 0 :(得分:0)
过去,我通过创建数据库视图完全解决了这个问题。您可以根据问题中的SQL创建数据库视图,然后将该数据库视图映射到“view”对象。
缺点是如果你需要操作和保存以这种方式检索的数据,你必须根据原始数据库表读取可操作对象,以便通过休眠来修改和保存它们。