Mybatis Plus各种查询方法

Stella981
• 阅读 774
package com.xiao.permission_system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.mysql.cj.util.StringUtils;
import com.xiao.permission_system.entity.UserInfo;
import com.xiao.permission_system.mapper.UserInfoMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;;

@RunWith(SpringRunner.class)
@SpringBootTest
public class PermissionSystemApplicationTests {

    @Test
    public void contextLoads() {
    }

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 普通查询
     */
    @Test
    public void selectById() {
        UserInfo userInfo = userInfoMapper.selectById(123);
        System.out.println(userInfo);
    }

    /**
     * 批量查询
     */
    @Test
    public void selectByIds() {
        List<Long> ids = Arrays.asList(123L,124L,125L);
        List<UserInfo> userInfo = userInfoMapper.selectBatchIds(ids);
        System.out.println(userInfo);
    }

    /**
     * 名字包含娟并且年龄小雨30
     */
    @Test
    public void selectByWrapper() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.like("username","娟").lt("age",30);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }
    /**
     * 名字包含娟并且年龄大雨等于20且小于等于40并且email不为空
     */
    @Test
    public void selectByWrapper2() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.like("username","娟").between("age",20,30).isNotNull("email");
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * 名字姓肖或者年量大雨等于20,按照年龄降序排列,年龄相同按照id生序排列
     */
    @Test
    public void selectByWrapper3() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.likeRight("username","肖")
                .or().ge("age",20).orderByDesc("age").orderByAsc("id");
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * 创建日期为2019年10月2日并且直属上级名字为王姓
     */
    @Test
    public void selectByWrapper4() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.apply("date_format(create_time,'%Y-%m-%d')={0}","2019-10-07")
                .inSql("parent_id","select id from user where username like '王%'");
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * 名字为王姓并且(年龄小于40或邮箱不为空)
     */
    @Test
    public void selectByWrapper5() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.likeRight("username","王")
                .and(wq->wq.lt("age",40))
                .or().isNotNull("email");
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }
    /**
     * 名字为王姓并且(年龄小于40并且大与20或邮箱不为空)
     */
    @Test
    public void selectByWrapper6() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.likeRight("username","王")
                .and(wq->wq.lt("age",40).gt("age",20))
                .or().isNotNull("email");
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }
    /**
     * (年龄小于40并且大与20或邮箱不为空)名字为王姓并且
     */
    @Test
    public void selectByWrapper7() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.nested(wq->wq.lt("age",40))
                .or().isNotNull("email")
                .likeRight("username","王");
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }
    /**
     * 年龄23,30,40
     */
    @Test
    public void selectByWrapper8() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.in("age",Arrays.asList(20,30,40));
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }
    /**
     * 只返回满足条件的其中一条语句即可
     */
    @Test
    public void selectByWrapper9() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.in("age",Arrays.asList(20,30,40)).last("limit 1");
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * 名字中包含雨并且年龄小于40(只取id,username)
     */
    @Test
    public void selectByWrapper10() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.select("id","username").like("username","雨").lt("age",40);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * 名字中包含雨并且年龄小于40(不取create_time,parent_id两个字段,即不列出全部字段)
     */
    @Test
    public void selectByWrapper11() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.like("username","雨").lt("age",40)
                    .select(UserInfo.class,info->!info.getColumn().equals("create_time")&&
                            !info.getColumn().equals("parent_id"));
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * 姓名和邮箱不为空
     */
    public void testCondition() {
        String username = "王";
        String email = "";
        condition(username,email);
    }

    private void condition(String username,String email){
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.like(StringUtils.isNullOrEmpty(username),"name",username)
                    .like(StringUtils.isNullOrEmpty(email),"email",email);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * 实体作为条件构造器方法的参数
     */
    @Test
    public void selectByWrapperEntity() {
        UserInfo whereUser = new UserInfo();
        whereUser.setUsername("xiaojuan");
        whereUser.setAge(22);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>(whereUser);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }
    /**
     * AllEq用法
     */
    @Test
    public void selectByWrapperAllEq() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("nuserame","xiaojuan");
        params.put("age",null);
        queryWrapper.allEq(params);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * AllEq用法(排除不是条件的字段)
     */
    @Test
    public void selectByWrapperAllEq2() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("nuserame","xiaojuan");
        params.put("age",null);
        queryWrapper.allEq((k,v)->!k.equals("name"),params);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * selectMaps
     */
    @Test
    public void selectByWrapperMaps() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.like("name","肖").lt("age",40);
        List<Map<String,Object>> userInfoList = userInfoMapper.selectMaps(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * 按照直属上级分组,查询每组的平均年龄,最大年龄,最小年龄。并且只取年龄总和小于500的组
     */
    @Test
    public void selectByWrapperMaps2() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.select("avg(age) avg_age","min(min) min_age","max(age) max_age")
                .groupBy("parent_id").having("sum(age)<{0}",500);
        List<Map<String,Object>> userInfoList = userInfoMapper.selectMaps(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * selectObjs
     */
    @Test
    public void selectByWrapperObjs() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.select("id","name").like("name","肖").lt("age",40);
        List<Object> userInfoList = userInfoMapper.selectObjs(queryWrapper);
        userInfoList.forEach(System.out::println);
    }

    /**
     * selectCount
     */
    @Test
    public void selectByWrapperCount() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.like("name","肖").lt("age",40);
        Integer count = userInfoMapper.selectCount(queryWrapper);
        System.out.println(count);
    }

    /**
     * selectOne
     */
    @Test
    public void selectByWrapperSelectOne() {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
        queryWrapper.like("name","肖").lt("age",40);
        UserInfo user = userInfoMapper.selectOne(queryWrapper);
        System.out.println(user);
    }

    /**
     * 使用Lambda
     */
    @Test
    public void selectLambda() {
       // LambdaQueryWrapper<UserInfo> lambda = new QueryWrapper<UserInfo>().lambda();
        LambdaQueryWrapper<UserInfo> lambda = new LambdaQueryWrapper<UserInfo>();
        lambda.like(UserInfo::getUsername,"娟").lt(UserInfo::getAge,40);
        List<UserInfo> userInfoList = userInfoMapper.selectList(lambda);
        userInfoList.forEach(System.out::println);
    }

    /**
     * 使用Lambda,名字为王姓(年龄小于40或邮箱不为空)
     */
    @Test
    public void selectLambd2() {
        LambdaQueryWrapper<UserInfo> lambda = new LambdaQueryWrapper<UserInfo>();
        lambda.like(UserInfo::getUsername,"娟")
                .and(lqw->lqw.lt(UserInfo::getAge,40).or().isNotNull(UserInfo::getEmail));
        List<UserInfo> userInfoList = userInfoMapper.selectList(lambda);
        userInfoList.forEach(System.out::println);
    }

    /**
     * 使用Lambda链式
     */
    @Test
    public void selectLambd3() {
        List<UserInfo> userInfoList = new LambdaQueryChainWrapper<UserInfo>(userInfoMapper)
                .like(UserInfo::getUsername,"娟").ge(UserInfo::getAge,20).list();
        userInfoList.forEach(System.out::println);
    }
}

Mybatis Plus各种查询方法

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
3年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这