Use CascadeType.MERGE and CascadeType.PERSIST depending on case

Multi tool use
Use CascadeType.MERGE and CascadeType.PERSIST depending on case
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
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.
you can use CascadeType.ALL ...
– Ashish Kumar
3 hours ago
Just be advised that with
CascadeType.ALL
, you may accidentally update an existing MyReferencedEntityDAO
to an undesired state (if the update request contains stale data for MReferencedEntityDAO
, for example)– crizzis
3 hours ago
CascadeType.ALL
MyReferencedEntityDAO
MReferencedEntityDAO
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
FYI stackoverflow.com/questions/13370221/…
– marekful
4 hours ago