I have a One-to-Many relationship between entities. When doing this JPQL query:
SELECT parent FROM Parent parent JOIN parent.child child WHERE ...
I get duplicate records when a parent has 2 children, only one when a parent have one child, none when there is no child (none when no child is fine). Note that there is no duplicate of Parent in the SQL database.
The entities are declared as follow:
@Entity(...)
public class Parent {
@Id
Long parentId;
@OneToMany(mappedBy = "parentID")
List<Child> children;
}
@Entity(...)
public class Child {a
Long parentId;
}
I omitted a lot of code for brevity's sake, but that should give you a strong idea of what I am trying to do. Note that the relationship is defined on the parent's side because I need the list of parents along with their children returned from the query.
You can get rid of the duplicates by using the
DISTINCT
keyword:EDIT: The
DISTINCT
keyword is used to remoe duplicates from query results regardless of teh reason for the existence of these duplicates. Sometimes the reason is duplicate DB entries. But more often, duplicates are the consequence ofJOIN
statements, so your use case is completely legitimate.However, you could avoid explicit joins and the
DISTINCT
keyword by making the relation bidirectional. Then you can use implicit joins through navigation: