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

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

问题描述

我在实体之间有一对多的关系.执行此 JPQL 查询时:

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

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

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

当父母有 2 个孩子时,我得到重复记录,当父母有一个孩子时只有一个,没有孩子时没有(没有孩子时没有).请注意,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/Hibernate 重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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