JPA/Hibernate duplicate records

好久不见. 提交于 2019-12-01 11:10:29

问题


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:


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...


来源:https://stackoverflow.com/questions/16341408/jpa-hibernate-duplicate-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!