亲宝软件园·资讯

展开

QueryWrapper常用方法

_沈 人气:3

QueryWrapper常用方法

MybatisPlus 使用QueryWrapper测试用例

一、ge、gt、le、lt、isNull、isNotNull

@Test
public void testQuery() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper
            .isNull("name")
            .ge("age", 12)
            .isNotNull("email");
        int result = userMapper.delete(queryWrapper);
    System.out.println("delete return count = " + result);
}

二、eq、ne

@Test
public void testSelectOne() {
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("name", "Tom");
    Useruser = userMapper.selectOne(queryWrapper);//只能返回一条记录,多余一条则抛出异常
    System.out.println(user);
}

三、between、notBetween

@Test
public void testSelectCount() {
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.between("age", 20, 30);
        Integer count = userMapper.selectCount(queryWrapper); //返回数据数量
    System.out.println(count);
}

四、like、notLike、likeLeft、likeRight

@Test
public void testSelectMaps() {
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper
            .select("name", "age")
            .like("name", "e")
            .likeRight("email", "5");
    List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);//返回值是Map列表
    maps.forEach(System.out::println);
}

五、orderBy、orderByDesc、orderByAsc

@Test
public void testSelectListOrderBy() {
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.orderByDesc("age", "id");
    List<User>users = userMapper.selectList(queryWrapper);
    users.forEach(System.out::println);
}

六、插入insert

@Test
public void save() {
    User user = new User();
    user.setAge(23);
    user.setEmail("344");
    user.setName("test");
    // 1.使用service新增
    userService.save(user);
    // 2.使用mapper 新增
    userMapper.insert(user);
}

七、删除remove

@Test
public void delete() {
    // 根据条件删除
    userService.remove(Wrappers.<User>query().lambda().eq(User::getAge, 3));
}

八、修改update

@Test
public void update() {
    User user = new User();
    user.setAge(23);
    user.setEmail("344");
    user.setName("test333");
    UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id","1");
    // 1.user 中封装修改的属性值, updateWrapper 中封装修改的条件参数值
    userService.update(user,updateWrapper);

    // 2.根据条件修改对应的参数属性值
    userService.update(Wrappers.<User>update().lambda().set(User::getName, "2").eq(User::getAge, 23));    
    // 3.判断参数是否为空,并进行修改     String name = "name";     userService.update(Wrappers.<User>update().lambda().set(StringUtils.isNotBlank(name),User::getName, name).eq(User::getAge, 23));
}

总结

加载全部内容

相关教程
猜你喜欢
用户评论