You need to enable JavaScript to run this app. 如何在Spring Boot和Hibernate中获取数据库行级锁避免同记录被多线程处理
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot和Hibernate中获取数据库行级锁避免同记录被多线程处理

问题结论

你的现有实现无法达到避免多线程重复处理同一行数据的目标,属于错误实现。


现有实现的核心问题
  • 查询操作未对目标行加锁,并发场景下多个线程会同时查询到同一条status为null的Employee记录,最终重复执行更新和处理逻辑。
  • updateEmployee方法中Thread.sleep(3000)的逻辑进一步放大了问题:查询到数据后间隔3秒才执行更新,这段时间内足以有大量其他线程拿到同一条未加锁的记录。
  • 虽然方法上加了@Transactional注解,但Hibernate默认查询不会自动加行锁,仅靠事务默认隔离级别无法解决行级并发竞争问题。

可行实现方案

你可以根据业务并发量选择以下两种方案:

方案1:悲观锁(实现简单,适合并发量较低的场景)

在查询时直接对目标行加排他锁,直到当前事务提交前,其他事务无法读取或修改该行数据。
修改后的Repository核心代码示例:

import javax.persistence.LockModeType;

@Override
@Transactional
public Employee findEmpToProcessAndUpdateStatus() {
    Session currentSession = entityManager.unwrap(Session.class);
    // 增加排序保证查询结果稳定
    String hql = "from Employee where status is null order by id asc";
    Query<Employee> query = currentSession.createQuery(hql, Employee.class);
    query.setMaxResults(1);
    // 为查询到的行加悲观写锁
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    Employee employee = query.uniqueResult();
    if (employee == null) {
        return null;
    }
    System.out.println("FETCHED : " + employee.getFirstName());
    employee.setStatus("INPROGRESS");
    // 无需单独调用update方法,事务提交时会自动同步持久化对象的变更
    return employee;
}

注意:使用该方案需要确保数据库使用支持行锁的引擎(如MySQL的InnoDB),避免升级为表锁降低并发性能。

方案2:乐观锁+条件更新(性能更高,适合高并发场景)

不需要加数据库锁,通过更新条件判断抢占处理权,只有更新行数为1时代表当前线程抢到了该行的处理资格,否则说明该行已经被其他线程处理。
核心代码示例:

@Override
@Transactional
public Employee findEmpToProcessAndUpdateStatus() {
    Session currentSession = entityManager.unwrap(Session.class);
    String hql = "from Employee where status is null order by id asc";
    Query<Employee> query = currentSession.createQuery(hql, Employee.class);
    query.setMaxResults(1);
    Employee employee = query.uniqueResult();
    if (employee == null) {
        return null;
    }
    // 带状态条件更新,只有status仍为null时才更新成功
    int updatedCount = currentSession.createQuery("update Employee set status = 'INPROGRESS' where id = :empId and status is null")
            .setParameter("empId", employee.getId())
            .executeUpdate();
    // 更新行数为1代表抢占成功
    if (updatedCount == 1) {
        System.out.println("FETCHED AND LOCKED: " + employee.getFirstName());
        employee.setStatus("INPROGRESS");
        return employee;
    }
    // 抢占失败返回null,上层可重试查询下一条
    return null;
}

额外优化建议
  • 不要在事务内添加Thread.sleep这类长等待逻辑,会拉长事务持有锁的时间,大幅降低并发能力,业务处理逻辑尽量放到事务外执行。
  • 增加异常兜底逻辑:如果业务处理失败,要把对应记录的status重置为null,避免记录永久卡在INPROGRESS状态无法被后续处理。
  • 可以给status字段加索引,提升查询过滤的性能。

内容的提问来源于stack exchange,提问作者Ankit Kadam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:54:01