Tuesday, March 1, 2011

Retrieve emebedded or component using Hibernate Criteria api

Hi! 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?

From stackoverflow
  • 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));
    
    Konstantin : Ok, but how come I can do a HQL and retrieve the Address directly? Why does not the same apply for queries?
    ChssPly76 : 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.

0 comments:

Post a Comment