Adam Arold
Adam Arold

Reputation: 30528

How do I create a Hibernate Criteria query where I have to filter through multiple relations?

Suppose I have an entity like this:

@Entity
@Table(name = "ITEMS")
public class Item  {
    @OneToMany(mappedBy = "item")
    private Set<ItemParameterValue> parameterValues;
}

It has a relation with ItemParameterValues:

@Entity
@Table(name = "ITEM_PARAMETER_VALUES", uniqueConstraints = @UniqueConstraint(columnNames = {"item_id", "parameter_id"}))
    public class ItemParameterValue {
        @ManyToOne
        @JoinColumn(name = "parameter_id")
        private ItemParameter parameter;
}

which has a relation with ItemParameter:

@Entity
@Table(name = "ITEM_PARAMETERS", uniqueConstraints = @UniqueConstraint(columnNames = "sid"))
public class ItemParameter {

}

So for example I have some Item which has a parameter value of "220" which has a parameter named "Voltage". I have to filter for 220 but the value 220 can belong to many parameters, I need the one which belongs to the parameter "Voltage".

I know I can do something like this (assuming I set up the proper aliases):

Criteria c = session.createCriteria(Item.class);
// ...
c.add(Restrictions.conjunction()
    .add(Restrictions.eq("item.parameterValue", "220"))
    .add(Restrictions.eq("item.parameterValue.parameter.sid", "Voltage")));

but it seems somewhat cumbersome to me. Is there a more convenient way to handle this kind of relation?

Upvotes: 0

Views: 700

Answers (2)

jelies
jelies

Reputation: 9290

Creating the appropiate alias, makes the criteria easier:

Criteria c = session.createCriteria(Item.class);
c.createAlias("parameterValues", "pv");
c.createAlias("pv.parameter", "p");
c.add(Restrictions.eq("pv.theProperty", "220")); // I don't see in your question the name of the property to perform filter
c.add(Restrictions.eq("p.sid", "Voltage"));

Additionally, Restrictions.conjunction() is not necessary, you aren't grouping AND with ORs or other complex conditions in this case.

Upvotes: 0

Firo
Firo

Reputation: 30813

instead of createalias you can use createcriteria to shorten it

Criteria c = session.createCriteria(Item.class)
    .createCriteria("parameterValues")
        .add(Restrictions.eq("theProperty", "220"))
        .createCriteria("parameter")
            .add(Restrictions.eq("sid", "Voltage"));

Upvotes: 1

Related Questions