【发布时间】:2021-07-08 10:32:42
【问题描述】:
我正在尝试插入与另一个实体具有一对一关系的实体列表。对于许多父实体,一对一映射对象可能是相同的。我期望在父外键中引用相同的子实体,但实际上正在创建重复的行。这是我的实体。
@Builder
@Entity
public class PaymentInfoType1 {
@Id
Long id;
LocalDate date;
@Column(precision = 15, scale = 2)
BigDecimal amount;
String reference;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "account", referencedColumnName = "id")
Account account;
}
@Builder
@Entity
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Account {
@Id
Long id;
@EqualsAndHashCode.Include
String name;
@EqualsAndHashCode.Include
String accountId;
}
我正在根据从不同系统收到的信息创建 PaymentInfoType1 列表。每个 PaymentInfoType1 都与它的 Account 一起创建,它可能具有完全相同的信息,但实时的对象不同。
当我这样做时:
PaymentInfoType1 first = // Created with some logic
Account account1 = // name = sample & accountId = 123
first.setAccount(account1);
PaymentInfoType1 second = // Created with some logic
Account account2 = // name = sample & accountId = 123
second.setAccount(account2);
// Both the above its own account object but the field have exactly same values.
List<PaymentInfoType1> list = List.of(first, second);
repo.saveAll(list);
我原以为 PaymentInfoType1 表中会有两行,Account 中会有一行,但发现 Account 也有两行。看起来 Equals 和 HashCode 在这种情况下没有任何作用。
当映射对象通过 equals/hashcode 相似时,如何处理以不插入重复行。
【问题讨论】:
标签: java hibernate jpa spring-data-jpa lombok