简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM