How to let JPArepository.save() do insert only and prevent update?

Viewed 2158

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.

2 Answers

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;
    }
}

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) {
    ....
}
Related