客户说在子表中不需要主键。因此,子表具有两列“ 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();
}
一个实体必须通过唯一键来标识。这不需要与任何数据库主键对应,但是必须有一个或多个唯一的列可用于标识实体。
如果不可能,则需要将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.
}