Retrieve emebedded or component using Hibernate Criteria api
Asked Answered
A

2

7

I have this class mapped as a entity, lets call it Person. Person has an embedded/component relation to Address. I am having trouble using a Criteria that would return Address objects. I have tried this:

Criteria.createCriteria(Address.class)

Which does not work. I guess I need to go through the entity but then I would need some kind of projection?

Criteria.createCriteria(Person.class).<<what goes here???>>

Suggestions?

Aeromarine answered 24/9, 2009 at 14:2 Comment(0)
C
6

Component's lifetime is controlled by its owner; they are NOT considered associations. You therefore cannot retrieve component by itself from a query. You can, however, use it in criteria.

Assuming your "Address" class is mapped as "address" within "Person", you could do something like:

Criteria.createCriteria(Person.class)
 .add(Restrictions.eq("address.street", street));
Cylindroid answered 24/9, 2009 at 16:19 Comment(2)
Ok, but how come I can do a HQL and retrieve the Address directly? Why does not the same apply for queries?Aeromarine
Because HQL has capabilities that Criteria API does not. Now, if you really want to return your Address alone at any cost, you can create a projection list for Person-based criteria that would contain every property of Address (and nothing else) and apply AliasToBeanResultTransformer to a result. But this is a lot of headache and nothing to show for it; I'd select full Person instead and extract Address (if that's what you need) in java code. Or go with HQL.Cylindroid
K
0

This is how one can retrieve or refer the property of embedded object in hibernate.

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
                Parent.class,"parent");
criteria.createAlias("embeddedObjectFieldName", "parent.embeddedObjectFieldName");

criteria.setProjection(Projections.projectionList()
                .add(Projections.groupProperty("parent.propertyOne"))
                .add(Projections.max("embeddedObjectFieldName.embeddedobjectproperty")));

Hope above clarifies

Kachine answered 12/9, 2013 at 15:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.