MybatisPlus的使用(MybatisPlus的配置,wrapper的使用和自定义sql)

常用配置

复制代码
#MybatisPlus
mybatis-plus:
  global-config:
        db-config:
          id-type: auto #设置主键自增长策略
  type-aliases-package: com.itheima.mp.domain.po #别名扫描包 用于在mapper.xml中不需要指定全类名而简写

Wrapper是一个包装器 其中封装了很多方法让我们能够做条件判断

java 复制代码
 @Test
    void testQuery(){
        QueryWrapper<User> wrapper = new QueryWrapper<User>()
                .select("id","username","info","balance")
                        .like("username", "o")
                                .ge("balance", 2000) ;

     userMapper.selectList(wrapper) ;
    }
java 复制代码
  @Test
    void testUpdate(){
        //要更新的数据
        User user = new User();
        user.setBalance(4000);
        //条件过滤
        UpdateWrapper<User> wrapper = new UpdateWrapper<User>().eq("username", "jack") ;
        //执行更新
        userMapper.update(user, wrapper) ;
    }
java 复制代码
 @Test
    void testUpdateWrapper(){
        UpdateWrapper<User> wrapper = new UpdateWrapper<User>()
                .setSql("balance = balance -200 ")
                        .in("id", List.of(1L,2L,4L)) ;

        userMapper.update(null,wrapper) ;
    }

推荐使用Lambda来改善代码的硬编码情况

java 复制代码
  @Test
    void testLamdomUpdateWrapper(){
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<User>()
                .setSql("balance = balance - 200 " )
                .in(User::getId, List.of(1L,2L,3L))
                ;
        userMapper.update(null, wrapper) ;
    }

自定义sql

java 复制代码
  @Test
    void testCustomSqlUpdate(){
        List<Long> ids = List.of(1L, 2L, 3L);
        int amount = 200 ;
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<User>();
        wrapper.in(User::getId, ids) ;
        userMapper.updateBalanceByIds(wrapper,amount) ;
    }

Mapper

其中前面每个参数的注解必须要写

java 复制代码
void updateBalanceByIds(@Param(Constants.WRAPPER) 
    LambdaUpdateWrapper<User> wrapper,@Param("amount") int amount);

Mapper.xml

${ew.customSqlSegment}为固定写法 用来拼接where语句

java 复制代码
    <update id="updateBalanceByIds">
        update user set balance = balance - #{amount} ${ew.customSqlSegment}
    </update>
相关推荐
Kuo-Teng10 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
Jooou10 小时前
Spring事务实现原理深度解析:从源码到架构全面剖析
java·spring·架构·事务
fie888910 小时前
基于MATLAB的狼群算法实现
开发语言·算法·matlab
gihigo199810 小时前
MATLAB中生成混淆矩阵
开发语言·matlab·矩阵
曾几何时`11 小时前
C++——this指针
开发语言·c++
盖世英雄酱5813611 小时前
commit 成功为什么数据只更新了部分?
java·数据库·后端
小冯的编程学习之路11 小时前
【C++】: C++基于微服务的即时通讯系统(1)
开发语言·c++·微服务
煎蛋学姐11 小时前
SSM网上旅游订票服务系统10r27(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·ssm 框架·网上旅游订票系统·旅游服务数字化
码上淘金11 小时前
在 YAML 中如何将 JSON 对象作为字符串整体赋值?——兼谈 Go Template 中的 fromJson 使用
java·golang·json
海南java第二人12 小时前
数据库范式详解:从冗余到规范的升华之旅
数据库·oracle·ffmpeg