Hibernate: Projection of a many-to-one in a Criteria

I am playing around with the hibernate Criteria API for the first time recently.

I was trying to do the equivalent of this HQL

"select t.userTbl from Task t"

userTbl property is a many-to-one from Task. The Task.userTbl relationship is lazy.

So I came up with this

Criteria criteria = session.createCriteria( Task.class, "t" );
criteria.setProjection( Projections.property( "t.userTbl" ) );
List results = criteria.list();

Unfortunately this does something different to HQL.

In HQL although the userTbl relationship is set to lazy in the mapping the HQL eagerly fetches and materialises non-proxy objects of UserTbl.

However in the Criteria I get a list of proxies back which I don't want. I fiddled around with setFetchMode but this didn't seem to be the right thing. Anyone have any idea how to do the above in a Criteria properly and get non-proxies back like HQL?


13.10.2009 17:32:07

Try to force a join between the task class and the userTbl.

14.10.2009 13:36:08
Tried the following but didn't work unfortunately. Criteria criteria = session.create.criteria( Task.class, "t" ); criteria.createAlias( "t.userTbl", "u" ); criteria.setProjection( Projections.property( "u" ) ); List results = session.list(); Digging through the code I'm forced to conclude that projection of an entity is not possible. Unfortunate really that HQL doesn't compile to a Criteria which is then executed. This would have made sure the Criteria provides the same/consistent functionality as HQL, which would be nice.
Mike Q 14.10.2009 21:13:49
Can you explain what failed? The docs have examples of projections: hibernate.org/hib_docs/v3/api/org/hibernate/Criteria.html
Miguel Ping 15.10.2009 09:02:56