Search code examples
javajpamergepersistence

JPA Merge including children


I have an entity (Person) which contains a list of addresses. The UI for this actually only allows one address to be entered per name.

The user can create a Person and then add the address. In the database I have one person row and one address row. The user can then update via the UI the address. I am calling merge on the entity manager so that the same person is used. The problem is that the address is not merged but a new line is added. Therefore I have one person row and two address rows. Only the second address row is valid.

My code for this relationship is:

@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}, mappedBy = "person")
@OrderBy("id asc")
private List<Address> addresses;

Can I add any annotation to force the children to be merged? Or do I have to do this manually myself?

Ideally in the scenario above I would have one row in the Person table and one row in the address table.

Thanks


Solution

  • merge() will merge into the existing object if the Id matches an existing object. Ensure the Id of the address is the same.

    Also, if you only have one address, why are you using a OneToMany, just use a OneToOne.