What is the correct method of dealing with situation like this:
I have a flow with 4 steps, each step is mapped to its entity class and is joined on one parent entity (ParentEntity is joined to each StepNEntity with one-to-one relationship). When proceeding to next step, current step gets saved to DB.
@Entity
public class ParentEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@OneToOne(mappedBy = "parentEntity")
private Step1 step1;
@OneToOne(mappedBy = "parentEntity")
private Step2 step2;
...
}
@Entity
public class Step1 {
@MapsId
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private ParentEntity parentEntity;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
...
}
@Entity
public class Step2 {
@MapsId
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private ParentEntity parentEntity;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
...
}
I have no problems with saving ParentEntity with Step1 to DB with repository.save()
. On second step when I try
parentEntity.setStep2(step2); // step2 is a model in my flow view
parentRepository.save(parentEntity); // produces org.hibernate.PersistentObjectException: detached entity passed to persist:
Similarly I get exception if I try
step2.setParentEntity(parentEntity);
step2Repository.save(step2);
CodePudding user response:
My issue was in annotation @MapsId
which I added by mistake. After manually setting ParentEntity
and removing said annotation my code works.