Why repository.delete( entity_With_Null_Id) kicks off SQL INSERT + DELETE
Using a repository and trying to delete an Entity with id==null kicks off 2 unnecessary SQL orders and no exception !
@Test
public void removeWithIdNull() {
// ARRANGE
Info infoWithIdNull = new Info("entity with id null");
List<Info> listA = infoRepository.findAll();
assertThat(listA, hasSize(0));
// ACT
infoRepository.delete(infoWithIdNull);
// ASSERT
List<Info> listResult = infoRepository.findAll();
assertThat(listResult, hasSize(0));
}
This generates the following SQLs : An INSERT and then a DELETE =>
DEBUG org.hibernate.SQL - insert into info (message, version, id) values (?, ?, ?)
TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [entity with id null]
TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [2] as [INTEGER] - [0]
TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [3] as [BIGINT] - [10]
DEBUG org.hibernate.SQL - delete from info where id=? and version=?
TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [1] as [BIGINT] - [10]
TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [2] as [INTEGER] - [0]
this really annoys me, why does Spring-Data-JPA does not check that the entity exists before deleting it, instead of doing a merge() ..
Code in Data-JPA SimpleJpaRepository which explains this behaviour:
@Transactional
public void delete(T entity) {
Assert.notNull(entity, "The entity must not be null!");
em.remove(em.contains(entity) ? entity : em.merge(entity));
}
this code seems over-simplified to me. What do you think ?