after several hours I have finally decided to post my problem, and see if anyone has had this problem before. This is very curious and I am not being able to spot the problem. I have a customer management system with the following entities:
BusinessUnit , Invoice, InvoiceItem, PictureFolder and Event
The relationships between them are as follows:
BusinessUnit--OtM-->InvoiceItem
BusinessUnit--OtM-->PictureFolder
BusinessUnit--OtM-->Event
Invoice--OtM-->InvoiceItem
InvoiceItem--MtO-->Event
PictureFolder--MtO-->Event
Event--Mto-->BusinessUnit
BusinessUnit is where all invoice items from one or severael invoices for a given businessunit go. Invoice, InvoiceItem and PictureFolder are hopefully selfexplanatory. Event serves us as an InvoiceItem holder for a given event (understanding that an event is anything that happens to a businessunit, such as any given repair to conduct). So an event may involve several invoice items corresponding to several BusinessUnits and Invoices.
Hope this model explanation is clear.
My problem is that when I persist an Invoice, where I have created one event (in the same usercase, saving it through a single persist() call to the Invoice object and relying on cascading features) the Event instance gets duplicated. The rest is written properly to the database (MySQL by the way).
The following are the weirdest results I have found:
At calling the persist method : persist(invoice) I make a comparison between the object passed to the method, and the resulting object of the call, say inv1 and inv2, being inv2 the resulting instance.
When checking the event instances for the BusinessUnit and BillableItem instances in inv1, the references point to the same object.
But when checking the same instance paths in the resulting instance inv2, two different instances are given back, which in turn corresponds to a ducplicate entry inserted in the MySQL 'events' table.
The ORM Mapping is done through annotations and are as follows:
BusinessUnit
@OneToMany(mappedBy="businessUnit",cascade=CascadeType.ALL,orphanRemoval=true) List events = new ArrayList();
Invoice
@OneToMany(mappedBy="invoice",cascade=CascadeType.ALL,orphanRemoval=true) List items= new ArrayList();
InvoiceItem
@ManyToOne(cascade=CascadeType.PERSIST) @JoinColumn(name="event_id") Event event;
Event
@ManyToOne @JoinColumn(name="businessUnit_id") BusinessUnit businessUnit;
Actually the relationship between BusinessUnit and Event seems redundant, then the relationship can be indirectly obtained through the invoiceItem instances. That can probably solve the problem, because what is apparently causing the duplicate entry is the instance hold by the businessunit.
That can be a solution. But I am open to any other solutions.
All this was quite difficult for me to explain in detail. Hope the problem is clear.
Thanks for your time and best regards,
Carlos.