Spring JPA / Hibernate transaction force insert instead of update

后端 未结 3 1378
小蘑菇
小蘑菇 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条回答
  • 2021-01-04 11:52

    Does this help?

    Set updatable = false on your PK column definition. Example:

    @Id
    @GeneratedValue
    @Column(name = “id”, updatable = false, nullable = false)
    private Long id;
    

    Setting your id non updatable will stop JPA from doing updates on your primary key, so thing about it.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-04 12:05

    Why not create a clone object which clones everything except your primary keys and then save this cloned object.

    Since the PK will not be present, an insert happens, instead of an update

    0 讨论(0)
提交回复
热议问题