JPA/Hibernate duplicate records

2019-02-20 15:39发布

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.

1条回答
来,给爷笑一个
2楼-- · 2019-02-20 15:55

You can get rid of the duplicates by using the DISTINCT keyword:

SELECT DISTINCT parent FROM Parent parent JOIN parent.child child WHERE ...

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 of JOIN 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:

SELECT parent FROM Parent parent WHERE parent.children...
查看更多
登录 后发表回答