2

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.

mgrstnr
  • 490
  • 1
  • 5
  • 23
  • FYI https://stackoverflow.com/questions/13370221/jpa-hibernate-detached-entity-passed-to-persist – marekful Jul 24 '18 at 10:09
  • you can use CascadeType.ALL ... – MyTwoCents Jul 24 '18 at 10:58
  • 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 Jul 24 '18 at 11:40

0 Answers0