Spring JPA / Hibernate transaction force insert instead of update

后端 未结 3 1398
小蘑菇
小蘑菇 2021-01-04 11:13

Edited. Whilst extending the base repository class and adding an insert method would work an more elegant solution appears to be implementing Persistable in the entities.

3条回答
  •  萌比男神i
    2021-01-04 11:57

    I never did that before, but a little hack, would maybe do the job.

    There is a Persistable interface for the entities. It has a method boolean isNew() that when implemented will be used to "assess" if the Entity is new or not in the database. Base on that decision, EntityManager should decide to call .merge() or .persist() on that entity, after You call .save() from Repository.

    Going that way, if You implement isNew() to always return true, the .persist() should be called no mater what, and error should be thrown after.

    Correct me If I'm wrong. Unfortunately I can't test it on a live code right now.

    Documentation about Persistable: http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Persistable.html

提交回复
热议问题