I am wondering if the following problem can be solved solely through the use of JPA Annotations and Spring Data's CrudRepository.
The following entity is newly created with every request:
@Entity
@Table(name = "my_entity")
public class MyEntityDAO {
....
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
@JoinColumn(name = "my_referenced_entity_id")
@JsonBackReference
private MyReferencedEntityDAO myReferencedEntity;
....
}
The CrudRepository is storing the entity plus its referenced element using.
myEntityRepository.save(myEntityDAO);
The problem is that this only works for newly created referenced (MyReferencedEntity) entities. In some cases this is desired, but sometimes this referenced entity will already exist causing a: detached entity passed to persist
When I set
CascadeType.MERGE
it works for the case that the entity exists, but fails when a new one needs to be created.
Is there a way to make this work without handling this operation programmatically using the .persist() and .merge() methods? I have already tried adding both CascadeTypes through annotations but it did result in the same errors.