Reputation: 1573
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
If the id does exists everything works fine
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
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