9

I am using JPArepository.save() to insert the record to the database but it will automatically update the existing record in the database. What I want to do is let it throw exception if there are records with same primary key in the database.

I searched the solution in Google and find a solution that said use saveAndFlush instead of save can solve it. However, it still update the existing record after I used saveAndFlush.

Michael Tsai
  • 751
  • 2
  • 11
  • 21
  • 1
    Does this answer your question? [Spring JPA / Hibernate transaction force insert instead of update](https://stackoverflow.com/questions/37253175/spring-jpa-hibernate-transaction-force-insert-instead-of-update) – M. Rizzo Feb 11 '22 at 13:57

2 Answers2

8

Finally, I've found the solution. I just implement Persistable interface and ovrride the isNew() to be always true.

Example:

@Entity
public class ChessGame implements Persistable<Long> {
 
    @Id
    private Long id;

 
    @Override
    public boolean isNew() {
        return true;
    }
}
Michael Tsai
  • 751
  • 2
  • 11
  • 21
0

There is no way to do just an INSERT without UPDATE in JPA out-of-the-box.

You need to define your own INSERT method on your JpaRepository and then call it from your code.

public interface MyRepository extends JpaRepository<MyRecord, Integer> {
    
    ....

    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "INSERT INTO my_table (field1, field2) "
        + "VALUES (:#{#c.field1}, :#{#c.field2})", nativeQuery = true)
    public void insert(@Param("c") MyRecord c);

}

And then in the code doing the insert:

final var newRecord = MyRecord.builder()
    .field1(...)
    ....
    .build();

try {
    myRepository.insert(newRecord);
} catch (DataIntegrityViolationException e) {
    ....
}
Adrian Smith
  • 17,236
  • 11
  • 71
  • 93