Java – hibernate onetomany standard returns duplicates
•
Java
I have an association mapped by:
@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 want to use the criteria API to return a list of all parent entities that contain one or more child entities with the attribute enabled = false I do not want to query a subset of filter mappings
For example, give 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 have used 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 returns 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
That is, it returns a single parent record (populating the subset) for each child element, where enabled = false
Who knows how to return only the unique parent element in this case?
Expressing appreciation for the proposal, P
Solution
You need to add a different, for example
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
It should suit your situation
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码