Using JPA with EclipseLink I have 2 classes: user and address.
Simplification in the same transaction, I create a new user, a new address and add this address to the user, knowing that each user can have many addresses:
User = new User(); Address address= new Address(); user.addAddress(address);
This is a mapping in the User class:
@OneToMany(mappedBy = "idUser") private Set<Address> addresses;
This is a mapping in the Address class:
@ManyToOne(cascade = { javax.persistence.CascadeType.REFRESH, javax.persistence.CascadeType.MERGE }) @JoinColumn(name = "id_user", referencedColumnName = "id", nullable = false) private User user;
I use Spring Data JPA Custom Repository, where I insert entitymanager and call from service:
public void saveUser(TUsuario user) { em.persist(user); }
After that I save the address
address.setDay(1); address.setMonth(2); address.setYear(3); address.setUser(user); public void saveUserAddress(Address address) { em.persist(address); }
And finally, when the service method is completed, the transaction is completed.
When I try to execute thansaction, an error occurs:
'A new object was found through a relationship that was not marked cascade PERSIST'
If I mark the list of user addresses as cascading PERSIST, then eclipselink tries to save the user twice (I think when I save the user and the second when the user address will be saved).
How can I do this for eclipselink so as not to save it, but detect it as an existing object?
PS: I tried to use merge instead of saving and did not work.