BIGE_BIGGER 2019-04-25 18:09 采纳率: 0%
浏览 2585
已结题

mysql 悲观锁 for update 无效问题

问题:springboot 项目,对数据库加行锁,多线程测试结果仍然是不安全的。

实体类:和数据库表对应,数据库表主键id建立了索引

@Entity
@Table(name = TableName.TABLE_SPORTRECORDID)
@JsonInclude(value= JsonInclude.Include.NON_EMPTY)
public class SportRecordId {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    //跑步记录的唯一Id
    private Integer useageid;
        //省去setter .getter
        }

Repository

@Repository
public interface SportRecordIdRepository extends PagingAndSortingRepository<SportRecordId, Integer> {

    @Query(nativeQuery=true,value = "select a.* from sportrecordid a where a.id = ?1 for update")
    Optional<SportRecordId> findSportRecordIdForUpdate(Integer id);
}

Service

     @Autowired
    private SportRecordIdRepository sportRecordIdRepository;

    @Override
    //@Transactional(isolation = Isolation.SERIALIZABLE)
    public Integer getSportRecordIdForUpdate(Integer id) {
        SportRecordId res  = sportRecordIdRepository.findSportRecordIdForUpdate(id).orElse(null);
        if(res!=null)
        {
            res.setUseageid(res.getUseageid()+1);
            SportRecordId saved = sportRecordIdRepository.save(res);
            return saved.getUseageid();
        }
        else
        {
            throw new ServiceException(ServiceErrorCode.SERVER_BUSY.getCode(),ServiceErrorCode.SERVER_BUSY.getMessage());
        }
    }

多线程测试
图片说明

  • 写回答

1条回答 默认 最新

  • dabocaiqq 2019-04-26 00:21
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog