Hibernate version:3.1
Here's the problem: I need to get my query results into a single bean (for some 3rd party package). At first it sounds easy, but I seem to have a few requirements that make it more difficult than expected. Let's say I have two classes, Cat & Owner. And let's say that I perform some arbitrary calculations in my HQL query. These calculation return scalar values. This is how the query might typically be written:
Code:
select a, (a.weight - a.owner.weight) as delta from Cat a
One of the problems here is that it returns an object array instead of it wrapped up in a bean. Remember that the 'delta' calculation can be any sort of arbitrary calculation so I can't map it in a formula in the hibernate mapping. So then I try something like this:
Code:
select new MyBean(a, (a.weight - a.owner.weight) as delta) from Cat a
This somewhat works, although I would prefer not to do everything in the constructor (more on that in a sec). But let's say I decide to deal with that and finish off my final requirement which says that Owner must be fetched eagerly AND through the 'join'. What I mean by this, is that when I get my Cat object, I want the Owner property to be already populated (through the join). I do not want it returned as a 'field' from the query. If I understand correctly, the mapping is ignored for the fetch method, so it must be done in HQL. So I try this:
Code:
select new MyBean(a, (a.weight - b.weight) as delta) from Cat a left join fetch a.owner b
Problem! This gives me an error saying that I requested join fetching but owner not in select list. In other words, it seems Cat being wrapped in the bean's constructor makes hibernate think that its not there.
In other words, the following does not throw an error, but does NOT meet my requirement.
Code:
select a from Cat a left join fetch a.owner b
Ideally, I would be able to do something like this (pseudo-hql). Is anything like this (arbitrarily assigning bean properties on the fly) possible in HQL?
Code:
select a, a.deltaWeigth = (a.weight - b.weight) from Cat a left join fetch a.owner b
So this leads me back to my original query. My only workaround is to post-process it. Something like:
Code:
List list = session.createQuery("select a , (a.weight - b.weight) as delta from Cat a left join fetch a.owner b")
for (Object[] objs : list) {
Cat cat = (Cat) objs[0];
Double delta = Double (objs[1]);
cat.setDelta1(delta);
}
Which should work, but I'm wondering if someone has a better, more effecient way. Hibernate seems to have a lot of options and can be difficult to know all of them.
Thank you