I have a problem with Groups containing GroupElements.
For example, with this data :
I try to list the Group and expect to get 2 Group with 3 GroupElement in each Group.
Instead, each Group is duplicated. I actually obtain 6 Group:
My guess is that a Group is rebuilt for each GroupElement.
I searched on SO and found that the problem could come from the equals()/hashCode() definition or from the way the request is written so I give you both.
I have this mapping :
@Entity
@Table(name = "xxx")
public class Group {
...
@JsonBackReference
@OneToMany(mappedBy = "group")
private List<GroupElement> groupElements = Lists.newArrayList();
//Getters & Setters
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || !o.getClass().equals(getClass())) {
return false;
}
return getId() != null && getId().equals(((HasId) o).getId());
}
@Override
public int hashCode() {
return getId() != null ? getId().hashCode() : super.hashCode();
}
}
I request groups like this :
public List<Group> listFull() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Group> query = cb.createQuery(Group.class);
Root<Group> group = query.from(Group.class);
group.fetch(Group_.groupElements, JoinType.LEFT);
return em.createQuery(query).getResultList();
}
I can fix it with an intermediate Set but I ask this question in order to find a better solution.
Set ResultTransformer to you (Hibernate)Criteria and you will get result without duplicates:
Session session = getSession();
Criteria criteria = session.createCriteria(clazz);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
If you are using JPA, try this:
CriteriaQuery<Group> query = cb.createQuery(Group.class);
query.distinct(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With