hibernate OneToMany criteria returns duplicates

I have an association mapped by the following:

@Entity
public class Parent
{
...
    @Id
    @Column(name = "parent_id")
    private Long id;

    @OneToMany(mappedBy = "parent")
    @OrderBy("id")
    private List<Child> children;
...
}

@Entity
public class Child
{
...
    @Id
    @Column(name = "child_id")
    private Long id;

    @ManyToOne
    @NotFound(action = NotFoundAction.IGNORE)
    @JoinColumn(name = "parent_id")
    private Parent parent;

    @Column
    private Boolean enabled;
...
}

I would like to use the Criteria API to return a list of all of the Parent entities which contain one or more Child entities with the attribute enabled=false . I would not like the mapped children collection to be filtered by the query.

For example, given the following:

Parent A
    - Child A enabled=true
    - Child B enabled=false

Parent B
    - Child A enabled=false
    - Child B enabled=false

Parent C
    - Child A enabled=true
    - Child B enabled=true

The query should return the following:

Parent A
    - Child A enabled=true
    - Child B enabled=false

Parent B
    - Child A enabled=false
    - Child B enabled=false

So far I am using the following Criteria query:

Criteria crit = session.createCriteria(Parent.class);
crit.createCriteria("children").add(Restrictions.eq("enabled", false));
List<Parent> result = crit.list();
return result;

However it is returning the equivalent of

Parent A
    - Child A enabled=true
    - Child B enabled=false

Parent B
    - Child A enabled=false
    - Child B enabled=false

Parent B
    - Child A enabled=false
    - Child B enabled=false

Ie, it is returning a single parent record (with the children collection populated) for each child element with enabled=false

Does anyone know how to only return unique parent elements in this scenario?

Advice appreciated, p.


You need to add a distinct , eg

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

should work in your case

链接地址: http://www.djcxy.com/p/6314.html

上一篇: 使用子查询条件查询Hibernate父/子

下一篇: 休眠OneToMany标准返回重复项