views:

84

answers:

1

Hi There, 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. i.e. List<Parent> findParents(Child child);

Thanks.

+1  A: 

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.

Tony Day