为什么JPA无法合并hibernate返回的多个(但相同)结果?

时间:2018-11-24 08:58:23

标签: java hibernate spring-boot jpa thymeleaf

我刚进入休眠状态。我在Spring Boot 1.5中使用了休眠模式,遇到一个奇怪的问题,我不知道如何解决。

在下图中,您将注意到重复了相同的电子邮件字段。 Database shows single entry of email address but appears twice in UI

用户模型对象

@Data
@Entity
@Table(name = "user")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, allowGetters = false)
@DynamicUpdate
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    ...

    private Boolean isActive;

    @OneToMany(mappedBy = "user", orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<UserEmail> emails = new ArrayList<>();

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "users_roles",
    joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles;

    public void addUserEmail(UserEmail email) {
        email.setUser(this);
        this.emails.add(email);
    }

    public void removeUserEmail(UserEmail email) {
        emails.remove(email);
        email.setUser(null);
    }
}

UserEmail模型对象

@Data
@Entity
@EntityListeners(AuditingEntityListener.class)
public class UserEmail {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @Email
    @NaturalId(mutable = true)
    @Column(name = "email", unique = true)
    private String email;
}

但是在数据库中,实际上并没有重复发送电子邮件。

以下是我想获取用户时执行的sql查询:

Hibernate: select user0_.id as id1_2_0_, user0_.created_at as created_2_2_0_, 
user0_.first_name as first_na3_2_0_, user0_.is_active as is_activ4_2_0_, 
user0_.last_name as last_nam5_2_0_, user0_.password as password6_2_0_, 
user0_.phone as phone7_2_0_, user0_.updated_at as updated_8_2_0_, 
user0_.username as username9_2_0_, emails1_.user_id as user_id3_4_1_, 
emails1_.id as id1_4_1_, emails1_.id as id1_4_2_, emails1_.email as 
email2_4_2_, emails1_.user_id as user_id3_4_2_, roles2_.user_id as 
user_id1_5_3_, role3_.id as role_id2_5_3_, role3_.id as id1_1_4_, role3_.name 
as name2_1_4_ from user user0_ left outer join user_email emails1_ on 
user0_.id=emails1_.user_id left outer join users_roles roles2_ on 
user0_.id=roles2_.user_id left outer join role role3_ on 
roles2_.role_id=role3_.id where user0_.id=1

这给我以下结果 two rows returned

在图片中,我们可以看到返回了两行。 hibernate构造的sql查询在某种程度上为每个角色获取了相同的电子邮件结果。我了解(并反复核对)这仅在具有多个角色的用户中才发生。现在,由于电子邮件相同,因此休眠/ jpa是否不应该正确识别并将这两封电子邮件合并为一封电子邮件?

如何解决此问题?任何帮助表示赞赏。我了解我的问题可能无法得到很好的解释,所以如果您有困惑,请提出。

0 个答案:

没有答案