JPA/休眠重复记录 [英] JPA/Hibernate duplicate records

查看:110
本文介绍了JPA/休眠重复记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在实体之间存在一对多关系.进行此JPQL查询时:

I have a One-to-Many relationship between entities. When doing this JPQL query:

从父级选择SELECT父级父级JOIN parent.child子级WHERE ...

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

当父母有两个孩子时,我得到重复的记录,当父母有一个孩子时,我只有一个记录,没有孩子时则没有(没有孩子时就没有).请注意,SQL数据库中没有Parent的重复项.

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.

实体声明如下:

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

推荐答案

您可以使用DISTINCT关键字来消除重复项:

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

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

DISTINCT关键字用于从查询结果中删除重复项,而不管这些重复项是否存在的原因.有时原因是重复的数据库条目.但是更常见的是,重复是JOIN语句的结果,因此您的用例是完全合法的.

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.

但是,通过使关系成为双向,可以避免显式联接和DISTINCT关键字.然后,您可以通过导航使用隐式联接:

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

这篇关于JPA/休眠重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆