作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
客户表示子表中不需要主键。所以子表有两列“ID”和“Value”,其中ID可以重复。
当我删除 @Id 时, hibernate 会显示“没有为实体指定标识符”
当我在代码中保留@Id时,hibernate会说“javax.persistence.EntityExistsException:具有相同标识符值的不同对象已与 session 关联”;在坚持的同时
关键是我需要保留@Id,但如何使用@Id注释在一个 session 中保留两个相同的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
)。进一步查看此处:
What is difference between @Entity and @embeddable
@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.
}
关于java - JPA/hibernate : How to persist duplicate values in same session for field having @Id annotation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59279041/
我是一名优秀的程序员,十分优秀!