Is there an alternative to using UNION in this SQL statement, using Hibernate 3?
I've 开发者_JAVA百科got a nasty query which joins three different queries. I don't think there's any Hibernate way to handle unions (we're using Hibernate 3.0.5), so the statement is written as an SQLQuery.
The reason we want a single statement rather than using 3 separate HQL statements so that we can use the Hibernate Criteria setFirstResult and setMaxResults methods.
Selecting only certain fields isn't necessary, so selecting f.* etc. would be fine if that makes it easier (although I would have to alias every column in order to avoid duplicate column names).
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)
);
In the past I have side stepped this issues completely by creating a database view. You could create a database view based on the SQL you have in your question, then simply map that database view to "view" object.
The drawback is if you need to manipulate and save the data retrieved in this manner you would have to read the manipulable objects based on the original database table in order to modify and save them through hibernate.
精彩评论