我正在尝试弄清楚如何在检索父级时使用hibernate标准来获取一组特定的子元素。我创建了以下示例实体:
父类
@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
}
儿童班
@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;
}
性别等级
@Entity
public class Gender {
@Id
@Column(name="GENDER_ID")
private long genderId;
@Column(name="GENDER_IND")
private String genderInd;
}
Hibernate标准
getSession()
.createCriteria(Parent.class)
.createAlias("children", "c")
.createAlias("c.gender", "g")
.add(Restrictions.eq("g.genderInd", "M"))
.list()
这个标准给了我一个父母的名单,这个父母有一个男性(“M”)孩子,并且它会返回每个父母的所有孩子。我怎样才能得到一份父母的名单,这些父母有一个男孩,只有在Parent.children中有男孩子?
答案 0 :(得分:4)
我搜索了几天的解决方案,我有同样的问题,我有一个带有一系列traductions的对象,我想用唯一的当前语言查询一个对象。
我找到了这个解决方案: https://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/filters.html
为我工作,这里有一个解决方案:
@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;
}
在您进行查询之前:
Session session = sessionFactory.getCurrentSession();
session.enableFilter("genderFilter").setParameter("gender", "M");
答案 1 :(得分:1)
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();