spring-data-jpa deleteById踩坑记录

434 阅读1分钟

问题列表

  • 重复删除抛出EmptyResultDataAccessException
  • 并发删除抛出ObjectOptimisticLockingFailureException

问题分析

接口CrudRepository中方法定义:

void deleteById(ID id);

SimpleJpaRepository中方法实现:

@Transactional
public void deleteById(ID id) {
	Assert.notNull(id, "The given id must not be null!");
	this.delete(this.findById(id).orElseThrow(() -> {
		return new EmptyResultDataAccessException(String.format("No %s entity with id %s exists!", this.entitynfo.getJavaType(), id), 1);
	}))
}

@Transactional
public void delete(T entity) {
	Assert.notNull(entity, "Entity must not be null!");
	if (!this.entityInformation.isNew(entity)) {
		Class<?> type = ProxyUtils.getUserClass(entity);
		T existing = this.em.find(type, this.entityInformation.getId(entity));
		if (existing != null) {
			// 删除数据
			this.em.remove(this.em.contains(entity) ? entity : this.em.merge(entity));
		}
	}
}

可以看到先执行查询再执行删除,重复删除时就会抛出异常,改成先判断是否存在,存在再删除 接口CrudRepository中api:

boolean existsById(ID id);

代码:

if (demoRepository.existsById(id)) {
	demoRepository.deleteById(id);
}

压测模拟数据库操作变慢的情况增大问题出现的概率,并发请求删除时,多个线程都查到有记录然后进入删除方法,方法执行完提交事务报错

ObjectOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

解决方法:手动重写删除方法

@Transactional
@Modifying
@Query(value = "delete from t_demo where id = :id", nativeQuery = true)
void deleteById(@NotNull Long id);