Hibernate Criterion中的OneToMany关系

我想弄清楚如何使用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;
}

休眠标准

getSession()
    .createCriteria(Parent.class)
    .createAlias("children", "c")
    .createAlias("c.gender", "g")
    .add(Restrictions.eq("g.genderInd", "M"))
    .list()

这个标准给了我一个拥有男性(“M”)孩子的父母名单,并且它为每个父母返回所有的孩子。 我怎样才能得到一个有男性孩子的父母名单,并且只有Parent.children中的男性孩子?


我搜索了解决方案的日子,我遇到了同样的问题,我有一个包含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");

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/37041.html

上一篇: Hibernate Criterion in OneToMany relationship

下一篇: Hibernate unable to delete parent/child self