Hibernate Criterion in OneToMany relationship
I am trying to figure out how to use hibernate criterion to get a specific set of child elements when I retrieve the parent. I have created the following example entities:
Parent Class
@Entity
public class Parent {
@Id
@Column(name="PARENT_ID")
private long parentId;
@Column(name="NAME")
private String name;
@OneToMany(mappedBy="parent")
private Set<Child> children
}
Child Class
@Entity
public class Child {
@Id
@Column(name="CHILD_ID")
private long childId
@ManyToOne
@JoinColumn(name="PARENT_ID")
private Parent parent;
@ManyToOne
@JoinColumn(name="GENDER_ID")
private Gender gender;
}
Gender Class
@Entity
public class Gender {
@Id
@Column(name="GENDER_ID")
private long genderId;
@Column(name="GENDER_IND")
private String genderInd;
}
Hibernate Criteria
getSession()
.createCriteria(Parent.class)
.createAlias("children", "c")
.createAlias("c.gender", "g")
.add(Restrictions.eq("g.genderInd", "M"))
.list()
This criteria gives me a list of Parents that have a male ("M") child, and it returns all of the children for each of those parents. How can I get a list of Parents that have a male child and only have the male children in the Parent.children set?
I searched days for the solution, i had the same problems, i have an object with a collection of traductions, and i wanted to query an object with the only current language.
I found this solution : https://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/filters.html
working for me, here a solution for you :
@Entity
public class Parent {
@Id
@Column(name="PARENT_ID")
private long parentId;
@Column(name="NAME")
private String name;
@OneToMany(mappedBy="parent")
@Filter(name="gender", condition="gender.genderInd=:gender")
private Set<Child> children
}
@Entity
@FilterDef(name="genderFilter", parameters=@ParamDef( name="gender", type="string" ) )
public class Child {
@Id
@Column(name="CHILD_ID")
private long childId
@ManyToOne
@JoinColumn(name="PARENT_ID")
private Parent parent;
@ManyToOne
@JoinColumn(name="GENDER_ID")
private Gender gender;
}
And before you do your query :
Session session = sessionFactory.getCurrentSession();
session.enableFilter("genderFilter").setParameter("gender", "M");
Criteria cr = getSession()
.createCriteria(Parent.class)
.createAlias("children", "c")
.createAlias("c.gender", "g");
Criterion Malechild = Restrictions.eq("g.genderInd", "M");
Criterion NFemaleChild = Restrictions.ne("g.genderInd", "F");
LogicalExpression andExp = Restrictions.and(Malechild, NFemaleChild);
cr.add(andExp);
List results = cr.list();
链接地址: http://www.djcxy.com/p/37042.html
上一篇: 休眠从onetomany中删除