Spring JpaRepositroy.save() does not appear to throw exception on duplicate saves

后端 未结 4 1831
遇见更好的自我
遇见更好的自我 2020-12-09 02:36

I\'m currently playing around on Spring boot 1.4.2 in which I\'ve pulled in Spring-boot-starter-web and Spring-boot-starter-jpa.

My main issue is that when I save a

4条回答
  •  爱一瞬间的悲伤
    2020-12-09 03:34

    Note that there are 3 scenarios here:

    First, if there is no choice(like the OP), i.e if you are setting your own id "manually", Spring Data JPA is assuming that you want to check if there are duplicates(hence the SELECT), so it will do a "(i)SELECT + (ii)INSERT" if there is no existing record or a "(i)SELECT + (ii)UPDATE" if there is already an existing record. In short, 2 SQLs!

    Second, which is cleaner & better, is to use an ID generator, for example:

     @Id
     @GeneratedValue(generator = "my-uuid")
     @GenericGenerator(name = "my-uuid", strategy = "uuid2")
     private UUID id;
    

    In that case, there is ALWAYS only 1 INSERT statement.

    Third, which has already been brilliantly answered by @adarshr, but is also more painful, is to implement Persistable(instead of Serializable), and implement the isNew() method. Also, 1 INSERT statement.

    Cheers

提交回复
热议问题