springboot快速入门-7.mybatis-plus常见语法

查询

通过ID获取对象

User user = userMapper.selectById(1);

通过条件构造器获取对象

条件为name等于张三,并且,age不等于21

LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(User::getName,"张三").ne(User::getAge,21);
User user = userMapper.selectOne(lambdaQueryWrapper);

通过条件构造器获取LIST

LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(User::getAge,21);
List<User> user = userMapper.selectList(lambdaQueryWrapper);

通过内置分页获取分页数据

Integer pageNum = 2;
Integer pageSize = 10;
Page<User> page = new Page<>(pageNum,pageSize);

LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(User::getAge,21);
IPage<User> iPage = userMapper.selectPage(page,lambdaQueryWrapper);

自己写SQL

User user = new User();
user.setName("李四");
user = userMapper.getUser(user);

在mapper/UserMapper.java中写

User getUser(User user);

在resources/mapper/UserMapper.xml中的mapper节点下写

<sql id="selectUser">
    select u.ID,u.NAME,u.AGE from TB_USER u
</sql>
<select id="getUser" parameterType="com.example.demo.love.entity.User">
    <include refid="selectUser"></include>
    <where>
        1=1
        <if test="id != null"> and u.ID=#{id}</if>
        <if test="name != null"> and u.NAME=#{name}</if>
        <if test="age != null"> and u.AGE=#{age}</if>
    </where>
</select>

添加

过于简单,不写例子了

删除

过于简单,不写例子了

修改

过于简单,不写例子了

上一篇:在jeecg-boot中使用代码生成器&mybatis-plus


下一篇:9 个技巧,解决 K8s 中的日志输出问题