【发布时间】:2019-12-11 04:46:13
【问题描述】:
客户说子表中不需要主键。所以 Child 表有两列“ID”和“Value”,其中 ID 可以重复。
当我删除 @Id 然后休眠说“没有为实体指定标识符”
当我在代码中保留@Id 时,hibernate 会说“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();
}
【问题讨论】:
-
那么您可能希望
CustomerAgreement成为Embeddable并使用ElementCollection。另外,删除Serializable;它没用而且会增加噪音。 -
Used ElementCollection(targetClass = CustomerAgreementComputerAttachments.class) .... 在 OneToMany .... 上使用 Embeddable ...
-
@chrylis-onstrike-: 它仍在要求 Id 注释
-
@chrylis-onstrike-: 然后说 Composite-id 类必须实现 Serializable: com.evry.integrator.snow.dao.model.CustomerAgreementComputerAttachments...
标签: java hibernate jpa primary-key