Why Spring Data does not throw an error when saving an entity with an ID that does not exists in the database?

Viewed 77

I have a test updating an entity, everything works fine if the record exists in the database, however, if the record does not exists, instead of trying an update, it does an insert, ignoring the ID field and updating it with the ID from the database.

Using MySQL.

A simple entity:

@Entity
public class DummyTable {

    public DummyTable() {
    }

    @Id
    @GeneratedValue
    private Integer id;

    @Column
    private String notes;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }
}

With JPA repo

public interface DummyTableRepository extends JpaRepository<DummyTable, Integer> {
}

And my test

class DemoApplicationTests {

    @Autowired
    private DummyTableRepository dummyTableRepository;

    @Test
    void contextLoads() {
        var dummyRegistry = new DummyTable();
        dummyRegistry.setId(100);
        dummyRegistry.setNotes("");

        var result = dummyTableRepository.save(dummyRegistry);

        Assertions.assertEquals(result.getId(), dummyRegistry.getId());
    }

}

My problem is, if the record does not exists, the entity gets added to the database with some ID

Example of ID being replaced

If the id does exists everything works fine

enter image description here

So, why is this the default behavior? according to the docs, if it finds and ID, it will try an update, I understand is not normal that the ID does not exists, but then why an error is not thrown?

1 Answers
Related