mysql 悲观锁 for update 无效问题 20C

问题: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个回答

BIGE_BIGGER
BIGE_BIGGER 毫无用处,不知道别乱评论!!
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐