Sleeping Criteria: Joining a Table Without Associated Association

I would like to use the hibernate api criteria to formulate a specific request that combines two objects. Let me say that I have two entities: Pet and Owner with an owner having many pets, but to a decisive extent this association does not appear in the Java or xml annotation.

With hql, I can select owners who have a pet named "fido" by specifying the connection in the request (instead of adding a set of pets to the owner class).

Can this be done using sleep criteria? If so, how?

Thanks J

+67
java hibernate hql criteria
Apr 6 '09 at 7:37
source share
5 answers

I understand that if you do this using HQL, you are creating a Cartesian connection to the filter, not an internal connection. Criteria requests do not support this.

+56
Apr 06 '09 at 10:20
source share

This is really possible with the criteria:

DetachedCriteria ownerCriteria = DetachedCriteria.forClass(Owner.class); ownerCriteria.setProjection(Property.forName("id")); ownerCriteria.add(Restrictions.eq("ownername", "bob")); Criteria criteria = getSession().createCriteria(Pet.class); criteria.add(Property.forName("ownerId").in(ownerCriteria)); 

Refresh . This actually performs a subquery instead of a join, but it allows you to use criteria for two objects that are not related to hibernation.

+72
Jan 20
source share

In NHibernate, you can use subqueries that are defined as DetachedCriteria. Not sure if it works the same in Java, most likely this is the same thing:

 DetachedCriteria pets = DetachedCriteria.For<Pet>("pet") .SetProjection(Projections.Property("pet.ownername")) .Add(/* some filters */ ); session.CreateCriteria(typeof(Owner)) .Add(Subqueries.PropertyIn("name", pets); 

It is assumed that it is connected to the name of the owner.

+1
Apr 15 '09 at 13:40
source share
 Criterion ownerCriterion = Restrictions.sqlRestriction(SELECT ownerId FROM Owner WHERE ownerName ='bob'); Criteria criteria = getSession().createCriteria(Pet.class); criteria.createCriteria("ownerId").add(ownerCriterion); 
0
May 20 '15 at 20:13
source share

There is a SQLCriterion that you can give arbitrary SQL and add to your Criteria . In the SQL string, the token {alias} "will be replaced by the alias of the root object."

-one
Apr 6 '09 at 11:38
source share



All Articles