Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate OneToMany criteria returns duplicates

Tags:

java

hibernate

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.

like image 940
pstanton Avatar asked Jun 08 '11 10:06

pstanton


1 Answers

You need to add a distinct, e.g.

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

should work in your case

like image 162
bertolami Avatar answered Sep 24 '22 01:09

bertolami