rekiem87
rekiem87

Reputation: 1573

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

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?

Upvotes: 1

Views: 937

Answers (1)

Carlos C&#225;rdenas
Carlos C&#225;rdenas

Reputation: 160

@GeneratedValue will ignore provided Id if it doesn´t exists and it will insert a record using the autoincrement approach of the db. If you want to change the behavior of the Ids, you would need to create your own sequence generator.

https://ntsim.uk/posts/how-to-use-hibernate-identifier-sequence-generators-properly

More info about the GeneratedValue https://www.tutorialandexample.com/hibernate-generatedvalue-strategies

Upvotes: 1

Related Questions