Customer said no Primary Key Required in Child Table. So Child table has two column "ID" and "Value" where ID can be duplicated.
When i remove @Id then hibernate says "No identifier specified for entity"
When i keep @Id in code then hibernate says "javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session" ; while persisting
So crux is that i need to keep @Id but how to persist two same ID in one session with @Id annotation.
Following is code:
Main Entity:
public class CustomerAgreement implements Serializable {
@OneToMany(mappedBy = "customerAgreement", orphanRemoval = true, fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST})
private List<CustomerAgreementComputerAttachments> autoAttachComputersFromOrganizations;
Composed Entity:
public class CustomerAgreementComputerAttachments implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@ManyToOne
@JoinColumn(name = "ID")
private CustomerAgreement customerAgreement;
Main Program:
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();
}