简体   繁体   中英

How do I create a criteria where the parameter is a member of a collection field on the table?

I have a class that has the following structure:

public class Machine {
    private Set<Line> lines;
}

Now what I want to to is create a query with Criteria where I can get all the machines that contain a specific line.

I noticed Criteria has a Restrictions.in() but that checks whether a field of the table is in a Collection and I want to do it the other way around.

Thanks for helping me out, Cheers, Stef

Following Hibernate documentation should help: http://docs.jboss.org/hibernate/orm/4.0/manual/en-US/html/querycriteria.html#querycriteria-associations

Basically you'll need to create a 2nd criteria that refers to the elements of lines of the Machine class. ie

Criteria machineCriteria = session.createCriteria(Machine.class);
Criteria lineCriteria = machineCriteria.createCriteria("lines");
lineCriteria.add(Restrictions.eq("fieldNameOfLineClass", valueOfFieldNameOfLineClass);
machineCriteria.list();

I find this syntax more meaningful as well as more compact. Presuming that you have the id of a Line instance in your hand this would get you what you want.

    // we have a Long lineId
    Criteria crit = session.createCriteria(Machine.class)
        .createAlias("lines", "line")
        .add(Restrictions.eq("line.id", lineId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM