问题
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?
回答1:
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));
回答2:
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
来源:https://stackoverflow.com/questions/1471892/retrieve-emebedded-or-component-using-hibernate-criteria-api