mybatisPlus做行锁

mybatisPlus做行锁

1. 需求

数据库表中有一个字段是一个逗号分隔的字符串,需要对这个字段的值做增删改的处理。首先要做查询,然后对这行数据加锁,业务逻辑处理后再更新。

2. 代码

引入依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;


public int edit(TableDto tableDto ) {

/**
Mybatis里面有提供SqlSessionTemplate,由于SpringBoot都是用的注解的方式注入,所以没有Spring-Mybatis.xml也就不需要配置,用Autowired直接自动注入即可。
*/

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;



        int i = 0;
        String flag = tableDto.getFlag();
        String code = TableDto.getCode();
        String oldCode = TableDto.getOldCode();
        String id= TableDto.getId();
        //根据id查询数据
        Wrapper<TableDo > wrapper = Wrappers.<TableDo >query().lambda()
                .eq(!CommUtil.isEmpty(id), TableDo ::getId, id)
                .last("FOR UPDATE");
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession();
        try {
            // 业务操作
            TableDo tableDo = tableMapper.selectOne(wrapper);
            //查询的 mtceCode
            String codeStr= tableDto.getCode();
            switch (flag) {
                case "add":
                    //新增
                    codeStr= codeStr+ "," + codeStr;
                    break;
                case "del":
                    //删除
                    codeStr.replace(code + ",", "").replace("," + code , "");
                    break; //可选
                case "upd":
                    //语句
                    codeStr.replace(oldCode, code);
                    break;
                default:
                    break;
            }

            tableDto.setCode(codeStr);
            Wrapper<TableDo > wrapperUpd = Wrappers.<tableDto>query().lambda()
                    .eq(!CommUtil.isEmpty(code), TableDo ::getCode, code);
            i = tableMapper.updateSelective(TableDo , wrapperUpd);
            sqlSession.commit(); // 释放所有锁
        } catch (Exception e) {
            sqlSession.rollback(); // 回滚事务,释放所有锁
        }
        return i;
    }

3. 注意

业务结束后需要释放锁

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值