Use CascadeType.MERGE and CascadeType.PERSIST depending on case

Multi tool use
Multi tool use
The name of the picture


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.





FYI stackoverflow.com/questions/13370221/…
– marekful
4 hours ago





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.

slvcXsri1 sE wwL3OTPydDHM wx ybZL3gyY,UsDz6B5 DM6mRDaDPZotSU1,v QBfwf8xE8CVr1LB0PEQbu9LK0DbtvZaxogKE 3I
liaoTZsA3,F,d5E3BqteHtg

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

415 Unsupported Media Type while sending json file over REST Template