spring-data-jpa deleteById踩坑记录

问题列表

  • 重复删除抛出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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值