Reputation: 1820
I have the following two entities, Parent and Child. Parent does not have a field child.
The child entity is defined like this:
@Entity
@Table(name = "child")
@Audited
public class Child extends BaseEntity {
@OneToOne
@JoinColumn(name = "application_id")
@MapsId
@NotAudited
private Parent parent;
....
I am writing a test, and I want to create a parent entity and a child entity, and save both. So I do the following:
parentRepository.save(parent);
Child child = new Child(parent);
childService.save(child);
But, I'm getting the following error:
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: io.manuel.Parent; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: io.manuel.Parent
The thing is, if I remove the annotation @MapsId, it works. What do I have to do to make it work with the annotation?
Upvotes: 0
Views: 407
Reputation: 27078
You need to do it this way
Parent savedParent = parentRepository.save(parent);
Child child = new Child(savedParent);
childService.save(child);
You have to get hold of the persisted object and use it. That is what the exception says, you are passing a detached(not persistent) entity to save. Here is a nice picture of different states an entity can be.
Upvotes: 1