MyBatis-Plus的使用

MyBatis-Plus学习笔记

一、MySQL

1、创建表
DROP TABLE IF EXISTS user;

CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
	age INT(11) NULL DEFAULT NULL COMMENT '年龄',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
	PRIMARY KEY (id)
);

2、插入数据
DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

二、代码生成器

1、导入依赖
<!--Web-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<!--mybatisPlus-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3.1</version>
</dependency>
<!--MybatisPlus代码生成器 依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.1</version>
</dependency>
<!--velocity依赖-->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.0</version>
</dependency>
<!--swagger依赖-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
<!--工具包-->
 <dependency>
     <groupId>cn.hutool</groupId>
     <artifactId>hutool-all</artifactId>
     <version>5.7.3</version>
 </dependency>
<!--安全框架Sa-ToKen-->
 <dependency>
      <groupId>cn.dev33</groupId>
      <artifactId>sa-token-spring-boot-starter</artifactId>
      <version>1.24.0</version>
 </dependency>




<!--=================================================================================-->
<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    
    <!--=======================扫描在java包下.xml文件所需==============================================-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    <!--=================================================================================-->
    </build>

说明:我们使用mybatis-plus 可以节省我们大量的代码,尽量不要同时导入mybatis和mybatis-plus因为版本有差异!

2、.yml文件所需配置

连接数据库!这一步和mybatis相同!

spring:
#  profiles:
#    active: dev
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/studentmanager?useUnicode=trun&characterEncoding=utf-8&useSSl=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8
    username: root
    password: 123456
  
 server:
  port: 8013
  #=================================以上为代码生成器所需配置===============================
  
# 配置日志  (默认控制台输出)
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#此处配置扫描.XML文件,注意的配合依赖包一起用
  mapper-locations: classpath:com/roleToken/GWL/mapper/xml/*.xml
  type-aliases-package: com.roleToken.GWL.entity

#mybatis:
#  mapper-locations: classpath:mapper/*.xml
#  type-aliases-package: com.example.demo3.pojo
#  configuration:
#    map-underscore-to-camel-case: true
server:
  port: 8013
  
  #配置(mybatisplus3.4.3.1版本)
mybatis-plus:
  # 配置逻辑删除
  global-config:
    db-config:
      logic-delete-field: deleted  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置实体类字段上加上@TableLogic注解)
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

3、代码生成器文件

代码生成器位置

package com.example.myplus;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill; 
import com.baomidou.mybatisplus.annotation.IdType; 
import com.baomidou.mybatisplus.annotation.TableField; 
import com.baomidou.mybatisplus.generator.AutoGenerator; 
import com.baomidou.mybatisplus.generator.config.DataSourceConfig; 
import com.baomidou.mybatisplus.generator.config.GlobalConfig; 
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig; 
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType; 
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; 
import java.util.ArrayList;


public class MyBatis {
    public static void main(String[] args) {
         // 需要构建一个 代码自动生成器 对象
        AutoGenerator mpg = new AutoGenerator();

        // 1、全局配置
        GlobalConfig gc = new GlobalConfig();

        String projectPath = System.getProperty("user.dir");//获取项目路径
        gc.setOutputDir(projectPath+"/src/main/java");//设置路径
        gc.setAuthor("郭文龙"); //设置作者
         gc.setOpen(false);//是否打开资源管理器
        gc.setFileOverride(false);// 是否覆盖原来生成的
        gc.setServiceName("%sService"); // 去Service的I前缀
        
        gc.setIdType(IdType.AUTO);//ID设为自增
        gc.setDateType(DateType.ONLY_DATE);//日期格式
        gc.setSwagger2(true);//配置swagger
        mpg.setGlobalConfig(gc);//全局配置


        //2、设置数据源
        DataSourceConfig dsc = new DataSourceConfig();
        //==============================修改数据库名称========
        dsc.setUrl("jdbc:mysql://localhost:3306/studentmanager?useUnicode=trun&characterEncoding=utf-8&useSSl=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc);

        //3、包的配置
        PackageConfig pc = new PackageConfig();
        //只需要改实体类名字 和包名 还有 数据库配置即可
        pc.setModuleName("GWL");//模块名
        //===========================修改位置信息============
        pc.setParent("com.example.myplus");//模块生成位置
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);//全局配置

        //4、策略配置
        StrategyConfig strategy = new StrategyConfig();
        //=================================修改表名=============
        strategy.setInclude("user");//设置要映射的表名
        strategy.setNaming(NamingStrategy.underline_to_camel);//下划线转驼峰命名
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//下划线转驼峰命名
        strategy.setEntityLombokModel(true);// 自动lombok;
        strategy.setLogicDeleteFieldName("deleted");//逻辑删除字段
        // 时间自动填充配置
        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(createTime); tableFills.add(updateTime);
        strategy.setTableFillList(tableFills);
        // 乐观锁
        strategy.setVersionFieldName("version");
        strategy.setRestControllerStyle(true);//controller是Restful风格
        strategy.setControllerMappingHyphenStyle(true);// localhost:8080/hello_id_2

        mpg.setStrategy(strategy);//全局配置
        
        //执行全局配置
        mpg.execute();

    }
}
4、测试增删查改

mapper层加注解

@Repository//代表持久层
@Mapper
public interface UserMapper extends BaseMapper<User> {

}

//或启动下
@MapperScan("com/roleToken/GWL/mapper"

增删查改

package com.example.myplus;

import com.example.myplus.GWL.entity.User;
import com.example.myplus.GWL.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@SpringBootTest
class MyPlusApplicationTests {

   //继承了BaseMapper, 所有的方法都来自己父类
    //我们也可以编写自己的扩展方法
    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        //参数是一个Wrapper , 条件构造器,这里我们先不用 --null
        //查询全部用户
        List<User> users = userMapper.selectList(null);
//        遍历输出
        users.forEach(System.out::println);
    }
    @Test
    public void testInsert(){
//        插入(添加)用户,主要数据库里主键设置为自增
        User user = new User();
        user.setName("郭文龙");
        user.setAge(18);
        user.setEmail("2335806038@qq.com");
//        更新个数
        int result = userMapper.insert(user);
        System.out.println(result);
        System.out.println(user);
    }
    //测试更新
    @Test
    public void testUpdate(){
//        修改用户信息
        User user = new User();
        user.setId(2L);
        user.setName("阿峧不是山交");
        //        注意:updateById()参数是 一个对象!,这里输出的还是更新个数
        int i = userMapper.updateById(user);
        System.out.println(i);

    }
    //删除操作,通过id
    @Test
    public void testDeleteById(){
        //通过id删除
        this.userMapper.deleteById(1);

        //通过多个id,一次删除多个数据
        ArrayList list = new ArrayList();
        list.add(2);
        list.add(3);
        this.userMapper.deleteBatchIds(list);

    }
    //测试条件删除,通过map
    @Test
    public void testDeleteByMap(){

        HashMap<String, Object> map = new HashMap<>();
        map.put("name","z1111113f");
        this.userMapper.deleteByMap(map);

    }
    
    
}

三、controller层常用方法

1、增删查改
package com.vuespringboot.GWL.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vuespringboot.GWL.entity.User;
import com.vuespringboot.GWL.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper userMapper;

    @GetMapping("/myTongJi")//查找全部员工
    public List<User> list() {
        return userMapper.selectList(null);
    }

    @PostMapping("/login")//登录验证=====================================登录验证
    public int login(@RequestBody User user) {
        User res = userMapper.selectOne(Wrappers
                .<User>lambdaQuery()
                .eq(User::getName, user.getName())
                .eq(User::getPassword, user.getPassword()));
        if (res==null){
            return -1;
        }else {
            return 1;
        }
    }

    @GetMapping("/emps")               //还能加默认值============================分页与查询
    public Page<User> testPage(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "6") Integer pageSize,
                               @RequestParam(defaultValue = "") String search){
        //参数一:当前页,======参数二:页面大小

        //获取该页
        Page<User> page = new Page<User>(pageNum,pageSize);

        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
//        如果关键字为空则查询全部,不为空就进行模糊查询,加了这个name和id为空,分页查询也能查,好像是这样
        if (StrUtil.isNotBlank(search)){
            wrapper.like(User::getName,search);
            wrapper.like(User::getName,search)
                    .or()
                    .like(User::getId,search);
        }
        //查询该页
        Page<User> userPage = userMapper.selectPage(page, wrapper);
                        //::为获取类中属性的语法糖
//        List<User> userList = userPage.getRecords();
        return userPage;
    }


    @PostMapping("/emp")//接收添加完成的成员信息=================添加员工
    public void jiaUser(@RequestBody User user) {
        userMapper.insert(user);

    }



    @DeleteMapping("/emp/{id}")//接收删除请求=================删除员工

    public void chuUse(@PathVariable long id) {
        userMapper.deleteById(id);

    }
    @PutMapping("/gai")//接收修改完成的信息====================修改员工
    public void GaiUser(@RequestBody User user) {
        userMapper.updateById(user);

    }
}
2、文件传输
    //    好像是获取端口号
    @Value("${server.port}")
    private String port;
    private static final String ip = "http://localhost";


    @PostMapping("/file")//文件上传=============================文件上传
    public Result<?> file(@RequestPart("files") MultipartFile files) throws IOException {

//        获取文件
        String fileName = files.getOriginalFilename();
//            方法一:存储路径
        //files.transferTo(new File("D:\\我下载的\\IDEA\\过程文件\\VueSpringBoot\\src\\main\\resources\\files\\"+fileName));

//        先生成一个唯一标识符,防止相同名称的文件会覆盖
        String flag = IdUtil.fastSimpleUUID();
        //方法二
//        user.dir   项目根路径
        String filePath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag + "_" + fileName;
//        把文件写入上传的路径
        FileUtil.writeBytes(files.getBytes(), filePath);
//        返回下载图片的URL(地址)
        return Result.success(ip + ":" + port + "/user/" + flag);
    }




//        通过唯一标识确认具体文件
    @GetMapping("/{flag}")//文件下载=====================文件下载
    public void getFile(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;//新建一个输出流
//        获取文件存放的路径
        String filePast = System.getProperty("user.dir") + "/src/main/resources/files/";
//        查询该路径下的所有文件的名称
        List<String> fileNames = FileUtil.listFileNames(filePast);
//        找到与唯一标识一致的文件
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try {
//            如果那个文件存在,则证明可以被下载
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
//                通过文件路径读取文件字节流
                byte[] bytes = FileUtil.readBytes(filePast + fileName);
//                通过输出流返回文件(字节流出去到浏览器,通过response相应,所以没有返回值类型)
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }

        } catch (Exception e) {
            System.out.println("文件下载失败");
        }

    }

三、扩展部分

1、主键生成策略
//    @TableId(type = IdType.AUTO)//主键自增,数据库的字段也必须设置为自增
//    @TableId(type = IdType.NONE)//该类型为未设置主键类型
//    @TableId(type = IdType.INPUT)//手动输入id
//以下2种类型、只有当插入对象ID 为空,才自动填充。     
//    @TableId(type = IdType.ASSIGN_UUID)//UUID,全局唯一。主键类型为 String,缺点字符串逐渐不易检索
//    @TableId(type = IdType.ASSIGN_ID)//默认使用雪花算法 ,主键类型为 Long 或 String
    private Long id;
//实体类中定义ID处

注意:

实体类字段上 @TableId(type = IdType.AUTO) ,数据库字段一定要是自增!

2、分页查询、解决跨域

MybatisPlusConfig.java加入分页插件配置

package com.example.myplus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//=================结果跨域问题
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//扫描我们的mapper文件夹
@MapperScan("com/example/myplus")
@Configuration
@EnableTransactionManagement//事务
public class MyPlusConfig implements WebMvcConfigurer {
    //mybatisPlus3.4.3.1写法
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        //注册乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        //分页插件   我们使用的是mysql数据库
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        return interceptor;
    }
    //======================跨域问题
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","REQUEST")
                .allowCredentials(false)
                .maxAge(3600)
                .allowedHeaders("*");
    }

}

测试方法

//分页查询(需要在MybatisPlusConfig类配置)
@Test
public void testPage(){
    //参数一:当前页,======参数二:页面大小
  
    //获取该页
    Page<User> page = new Page<User>(2,3);
    //查询该页
    Page<User> userPage = this.userMapper.selectPage(page, null);
    //获得记录
    List<User> userList = userPage.getRecords();
    for (User user : userList) {
        System.out.println(user);
    }
}

还提供了其他方法

3、逻辑删除

**物理删除:从数据库中直接移除 **

逻辑删除:在数据库中没有被移除,而是通过一个变量让他生效!deleted=0 --> deleted=1

管理员可以查看被删除的记录!防止数据的丢失!类似于回收站!

1、在数据库表中增加一个deleted字段(默认值为0)

2、实体类中添加属性

@TableLogic // 逻辑删除private Integer deleted;

3、配置(mybatisplus3.4.3.1版本)

mybatis-plus:  # 配置逻辑删除  global-config:    db-config:      logic-delete-field: deleted  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置实体类字段上加上@TableLogic注解)      logic-delete-value: 1 # 逻辑已删除值(默认为 1)      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

结果走的是更新操作,不是删除操作,会将deleted字段设置为1,逻辑上删除

4、乐观锁&悲观锁

MybatisPlusConfig.java加入配置

package com.example.myplus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

//扫描我们的mapper文件夹
@MapperScan("com/example/myplus")
@Configuration
@EnableTransactionManagement//事务
public class MyPlusConfig {
    //mybatisPlus3.4.3.1写法
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        //注册乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        //分页插件   我们使用的是mysql数据库
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        return interceptor;
    }

}

测试

//测试乐观锁(需要在MybatisPlusConfig类配置)
@Test
public void testOptimisticLockerInner(){
    //乐观锁进行修改前会先查询,取出version的值,
    //然后进行修改更新信息的时候会比较version的值是否和之前查询的时候的version值一致
    //如果是一致则修改更新信息并且version的值+1
    //如果不是则修改信更新息失败

    //线程一
    User user = this.userMapper.selectById(1L);
    user.setName("zfStart1111");
    user.setEmail("123123123");

    //线程二,模拟插队操作
    User user2 = this.userMapper.selectById(1L);
    user2.setName("zfStart2222");
    user2.setEmail("22222");
    this.userMapper.updateById(user2);

    //有乐观锁的存在,在被其他线程插队的情况下,修改更新信息失败
    this.userMapper.updateById(user);
}

5、时间属性自动填充

创建时间 . 修改时间! 这些个操作都是自动化完成的,我们不希望手动更新!

阿里巴巴开发手册:所有的数据库表:gmt_create .gmt_modified几乎所有的表都要配置上!而且需要自动化!

方式一

方式一:数据库级别

1.在表中新增字段 create_time , update_time

2.再次测试插入方法,我们需要先把实体类同步

private Data creatTime;private Data updateTime;

方式二

方式二:代码级别

1.删除数据库默认值

将自动给出默认值打的钩子去掉

2.实体类字段属性上添加注解

//记住用util包下的Date!!
//字段添加填充内容
//添加用户时添加时间(需要在MyMetaObjectHandler类配置)
@TableField(fill = FieldFill.INSERT)
private Date createTime;

//添加用户或更新用户时添加时间(需要在MyMetaObjectHandler类配置)
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;1

3.编写处理器来处理这个注解

package com.codeyuaiiao.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component //把处理器加到IOC容器中
public class MyMetaObjectHandler implements MetaObjectHandler {

    //插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("Start insert fill.... ");
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    //更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("Start update fill.... ");
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

之后更新插入操作会自动填充操作时间

6、执行 SQL 分析打印

我们在平时的开发中,会遇到一些慢sql.

MP也提供了性能分析插件,如果超过这个时间就停止运行!

四、条件构造器

十分重要:wrapper

我们写一些复杂的sql就可以使用它来代替!

package com.example.myplus;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.myplus.GWL.entity.User;
import com.example.myplus.GWL.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


import java.util.List;


@SpringBootTest
public class WrapperTest {

    @Autowired
    private UserMapper userMapper;

    //条件查询
    @Test
    void testGe() {
        //查询name和邮箱不为空,年龄大于12岁的用户
//        这步好像必须要
        QueryWrapper<User> wrapper = new QueryWrapper<>();//和map有点相似
//        添加查询条件
        wrapper.isNotNull("name")
                .isNotNull("email")
                .ge("age", 12);//大于等于 greater是大于,equal是等于
        userMapper.selectList(wrapper).forEach(System.out::println);
    }

    //条件查询
    @Test
    public void testEq() {
        //查询名字
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name", "Sandy");
//        这个查询只能查一个人的,如果查询结果个数不唯一会报红
        User user = this.userMapper.selectOne(wrapper);
        System.out.println(user);
    }



    //查询年龄在10-20岁之间
    @Test
    void testBetWeen() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between("age", 10, 20);//区间
        List<User> userList = this.userMapper.selectList(wrapper);//查询到的用户集合
        for (User user : userList) {
            System.out.println(user);
        }
    }


    //模糊查询===============================================================
    @Test
    public void testLike() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.likeLeft("name", "龙");  //name like '%zf'

        List<User> userList = this.userMapper.selectList(wrapper);
        for (User user : userList) {
            System.out.println(user);
        }
    }

    //内查询(可以多表联查)
    @Test
    public void testInSql() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.inSql("id", "select id from user where id <20");

        List<User> users = this.userMapper.selectList(wrapper);
        for (User user : users) {
            System.out.println(user);
        }
    }


    //排序
    @Test
    public void testOrderBy() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //通过id进行降序排序
        wrapper.orderByDesc("id");

        List<User> users = this.userMapper.selectList(wrapper);
        for (User user : users) {
            System.out.println(user);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值