[英]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. 现在,我要使用Criteria创建一个查询,在其中可以获取包含特定行的所有计算机。
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. 我注意到Criteria有一个Restrictions.in(),但是它检查表的字段是否在Collection中,而我想用另一种方法来做。
Thanks for helping me out, Cheers, Stef 感谢您的帮助,干杯,Stef
Following Hibernate documentation should help: http://docs.jboss.org/hibernate/orm/4.0/manual/en-US/html/querycriteria.html#querycriteria-associations 下列Hibernate文档应该会有所帮助: 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. 基本上,您需要创建一个第二个条件,该条件引用Machine类的各
lines
元素。 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.
假设您手中有Line实例的ID,这将为您提供所需的东西。
// we have a Long lineId
Criteria crit = session.createCriteria(Machine.class)
.createAlias("lines", "line")
.add(Restrictions.eq("line.id", lineId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.