mybatis-plus-利用条件构造器自定义SQL

一、介绍

LambdaQueryWrapper避免了QueryWrapper的硬编码问题

@SpringBootTest
class MybatisPlusTestApplicationTests {

    @Autowired
    private TestService testService;

    @Test
    void test01() {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper
                .ge(User::getAge, 20)
                .or(i -> i.eq(User::getName, "lxm").eq(User::getAge, 10));
        List<User> userList = testService.list(lambdaQueryWrapper);
        userList.forEach(System.out::println);
    }

    @Test
    void test02(){
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        //eq的第一个参数为硬编码	
        queryWrapper.eq("age", 20);
        List<User> userList = testService.list(queryWrapper);
        userList.forEach(System.out::println);
    }

}

二、使用

数据库表结构及数据
mybatis-plus-利用条件构造器自定义SQL_第1张图片

(1)实体类

@Data
@TableName("t_user")
public class User {
    private Long id;
    private String name;
    private Integer age;
}

(2)根据通用Service和通用Mapper创建对应的Service和Mapper

@Mapper
public interface TestMapper extends BaseMapper<User> {

    List<User> selectAllUser(@Param(Constants.WRAPPER) Wrapper wrapper);
}
public interface TestService extends IService<User> {

    List<User> getUserList(Wrapper wrapper);
}
@Service
public class TestServiceImpl extends ServiceImpl<TestMapper, User> implements TestService {

    @Autowired
    private TestMapper testMapper;

    @Override
    public List<User> getUserList(Wrapper wrapper) {
        return testMapper.selectAllUser(wrapper);
    }
}

(3)编写Mapper的xml文件


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wsh.mybatisplustest.mapper.TestMapper">

    <select id="selectAllUser" resultType="user">
        select *
        from t_user
        ${ew.customSqlSegment}
    select>
mapper>

(4)运行

@SpringBootTest
class MybatisPlusTestApplicationTests {

    @Autowired
    private TestService testService;

    @Test
    void contextLoads() {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper
                .ge(User::getAge, 20)3
                //嵌套or
                .or(i -> i.eq(User::getName, "lxm").eq(User::getAge, 10));
        List<User> userList = testService.getUserList(lambdaQueryWrapper);
        userList.forEach(System.out::println);
    }

}

(5)日志输出

==>  Preparing: select * from t_user WHERE (age >= ? OR (name = ? AND age = ?))
==> Parameters: 20(Integer), lxm(String), 10(Integer)
<==    Columns: id, name, age
<==        Row: 1, wsh, 21
<==        Row: 2, tqs, 22
<==        Row: 3, lxm, 10
<==      Total: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@12d1f1d4]
User(id=1, name=wsh, age=21)
User(id=2, name=tqs, age=22)
User(id=3, name=lxm, age=10)

你可能感兴趣的:(mybatis-plus,mybatis-plus)