java - JPA/Hibernate:如何在同一会话中为具有 @Id 注释的字段保留重复值?
问题描述
客户说子表中不需要主键。所以 Child 表有两列“ID”和“Value”,其中 ID 可以重复。
当我删除@Id 然后休眠说“没有为实体指定标识符”
当我在代码中保留@Id 时,休眠会说“javax.persistence.EntityExistsException:具有相同标识符值的不同对象已与会话相关联”;在坚持的同时
所以关键是我需要保留@Id,但是如何使用@Id 注释在一个会话中保留两个相同的ID。
以下是代码:
主要实体:
public class CustomerAgreement implements Serializable {
@OneToMany(mappedBy = "customerAgreement", orphanRemoval = true, fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST})
private List<CustomerAgreementComputerAttachments> autoAttachComputersFromOrganizations;
组成实体:
public class CustomerAgreementComputerAttachments implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@ManyToOne
@JoinColumn(name = "ID")
private CustomerAgreement customerAgreement;
主程序:
public static List<CustomerAgreement> create() {
List<CustomerAgreement> li = new ArrayList<CustomerAgreement>();
CustomerAgreement cAgreement = new CustomerAgreement();
cAgreement.setId(2222l);
cAgreement.setName("Tillu");;
cAgreement.setCustomerId("140");
List<CustomerAgreementComputerAttachments> catl = new ArrayList<>();
CustomerAgreementComputerAttachments catt = new CustomerAgreementComputerAttachments();
catt.setAttachmentValue("TEST");
catt.setCustomerAgreement(cAgreement);
CustomerAgreementComputerAttachments tatt = new CustomerAgreementComputerAttachments();
tatt.setAttachmentValue("TESTy");
tatt.setCustomerAgreement(cAgreement);
catl.add(catt);
catl.add(tatt);
cAgreement.setAutoAttachComputersFromOrganizations(catl);
li.add(cAgreement);
return li;
}
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("IntegratorMasterdataPU");
em = emf.createEntityManager();
em.getTransaction().begin();
for(CustomerAgreement ca: create()) {
em.persist(ca);
}
em.getTransaction().commit();
}
解决方案
实体必须可以通过唯一键识别。这不需要对应于任何数据库主键,但必须有一个或多个唯一列可用于标识实体。
如果这是不可能的,那么你需要制作CustomerAgreementComputerAttachment
一个@Embeddable
.
一个@Embeddable
不同的实体没有独立的身份(没有@ID
)。在这里进一步查看:
@Entity
public class CustomerAgreement {
@ElementCollection
@JoinTable(name="...", joinColumn = "id")
private List<CustomerAgreementComputerAttachment> attachments;
}
和
@Embeddable
public class CustomerAgreementComputerAttachments {
//No back reference to CustomerAgreement
//Other fields as required.
}
推荐阅读
- javascript - React Native - 具有并行平移和缩放的动画
- netsuite - 已保存搜索以提取日期发票已全额支付
- r - 循环以识别 Dataframe 中的数据位置,并填充到新的 Dataframe (R)
- ruby - Ruby 套接字在第二次读取时不返回数据
- python - 在 conda/pip 中安装单个文件包需要多余的 import 语句
- indexing - 可以通过从 DataFlow 管道运行的 DatastoreV1 接口创建具有复合索引的 Google 数据存储实体吗?
- php - 如何在相应的输入下显示输入验证错误?
- javascript - 为什么 [] == ![] 在 JavaScript 中为真?
- python - 从 QTreeView 中的选择中获取完整的索引名称
- python - 使用 Python 将大型压缩 JSON 文件从 Amazon S3 导入 AWS RDS-PostgreSQL