Hibernate Criteria query on association
How would I go about executing the following Hibernate query using the criteria API. I have an object Parent with List children. I would like to search through all parents and find which parents contain a specified child. ie List<Parent> findParents(Child child);
Thanks.
This seems to work for me. The Product is the Parent and the Ingredient is the Child. It will hopefully find all Products which contain the given Ingredient. I've not been able to test this fully however.
public IList<Product> GetProductsWithIngredient(Ingredient ingredient)
{
using (ITransaction transaction = session.BeginTransaction())
{
ICriteria criteria = session.CreateCriteria<Product>();
criteria.CreateCriteria("Ingredients")
.Add(Restrictions.Eq("GUID", ingredient.GUID));
return criteria.List<Product>();
}
}
Hope this helps :)
NOTE: The GUID is my unique identifier.
EDIT: I've just tested this with more than one Product and it appears to return the correct product. Thanks to zoidbeck.
In Java its like this:
Criteria criteria = session.createCriteria(Parent.class,"parent")
.createAlias("child","child")
.add(Restriction.eq("child.name",child.getName());
List<Parent> parents = criteria.list();
should give you the answer.
链接地址: http://www.djcxy.com/p/37074.html