MybatisPlus——自定义Sql

MybatisPlus——自定义Sql

自定义sql

mybatisplus自定义sql并不是全部进行自定义的,我们可以利用MybatisPlus的Wrapper来构建复杂的Where条件,然后自己定义sql语句中剩下的部分。

自定义sql案例

以为例:将id在指定范围(1,2,6,9)的用户的年龄加上指定值(1,5)
1.mybatis中的写法
    <update id="updateUserById">
        update a_user
        set  age = age - #{num}
        where id in (
        <foreach collection="list" item="id" separator=",">
            #{id}
        </foreach>
        )
    </update>
 2.完全用Wrapper生成写法
    @Test
    void testUpdateWrapper() {
        System.out.println(("----- delete method test ------"));

        List<Integer> ids = List.of(1, 2, 6, 9);

        UpdateWrapper<User> wrapper = new UpdateWrapper<User>()
                .setSql("age = age + 1")
                .in("id", ids);

        int update = userMapper.update(null, wrapper);

        System.out.println("update = " + update);

    }

 为了避免sql语句写在业务逻辑层,一般不会采用上述方法

MP自定义sql的应用场景

而MP擅长的是where条件的构建,在一些特殊的场景下,mp使用起来会十分麻烦,所以我们可以采用把where条件相关的交给mp,一些其他的复杂sql语句我们自己来定义。

MP自定义sql步骤
1.基于Wrapper构建where条件
    @Test
    void testCustomUpdateWrapper() {
        System.out.println(("----- delete method test ------"));

        //1.更新的数据
        List<Integer> ids = List.of(1, 2, 6, 9);
        int num = 2;
        //2.更新的条件
        QueryWrapper<User> wrapper = new QueryWrapper<User>().in("id", ids);
        //3.调用自定义sql方法
        int update = userMapper.updateAgeById(wrapper,num);

    }
2.在mapper方法参数中用Param注解声明wrapper变量名称,必须是ew
@Mapper
public interface UserMapper extends BaseMapper<User> {
    int updateAgeById(@Param("ew") QueryWrapper<User> wrapper,@Param("num") int num);
}
3.自定义sql,并使用Wrapper条件
    <update id="updateAgeById">
        update a_user
        set  age = age + #{num} ${ew.customSqlSegment}
    </update>
4.更新结果
 

 

  • 31
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值