Question

I'd like to use Hibernate's Criteria API for precisely what everybody says is probably its most likely use case, applying complex search criteria. Problem is, the table that I want to query against is not composed entirely of primitive values, but partially from other objects, and I need to query against those object's id's.

I found this article from 2 years ago that suggests it's not possible. Here's how I tried it to no avail, there are other aspect of Hibernate where I know of where this sort of dot notation is supported within string literals to indicate object nesting.

   if (!lookupBean.getCompanyInput().equals("")) {
       criteria.add(Restrictions.like("company.company", lookupBean.getCompanyInput() + "%"));
   }

EDIT:

Here's my correctly factored code for accomplishing what I was trying above, using the suggestion from the first answer below; note that I am even using an additional createCriteria call to order on an attribute in yet another associated object/table:

if (!lookupBean.getCompanyValue().equals("")) {
    criteria.createCriteria("company").add(
           Restrictions.like("company", lookupBean.getCompanyValue() + "%"));
}

List<TrailerDetail> tdList = 
        criteria.createCriteria("location").addOrder(Order.asc("location")).list();
Was it helpful?

Solution

Not entirely sure I follow your example, but it's certainly possible to specify filter conditions on an associated entity, simply by nesting Criteria objects to form a tree. For example, if I have an entity called Order with a many-to-one relationship to a User entity, I can find all orders for a user named Fred with a query like this:

List<Order> orders = session.createCriteria(Order.class)
    .createCriteria("user")
        .add(eq("name", "fred"))
    .list();

If you're talking about an entity that has a relationship to itself, that should work as well. You can also replace "name" with "id" if you need to filter on the ID of an associated object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top