mybatis_plus基础使用

目录

1. MybatisPlus简介与特性

1.1 简介

2. MybatisPlus的开发环境搭建

2.1 数据库创建categor表

2.2 创建SpringBoot工程

2.3 mybatis_plus提供基础结构代码自动生成

2.4 配置数据库来源application.yml

3. 开始代码编写 

1 相等判断

 2 范围判断

 3 模糊匹配

4 非空判断 

 5 in判断

6 分组

7 排序

 8 条件判断

9 逻辑判断

10 存在判断

 11 查询字段


1. MybatisPlus简介与特性

1.1 简介

MybatisPlus作为MyBatis的一款增强工具,就是为了简化开发,为提高效率而生。同时还提供通用的Mapper与Service,无需写SQL的情况下对表进行增删改查,可以说是十分之优秀。简而意之就是减少基础crud方法的大量重复代码编写

2. MybatisPlus的开发环境搭建

2.1 数据库创建categor表


CREATE TABLE `category`  (
  `id` bigint(0) NOT NULL COMMENT '主键',
  `type` int(0) NULL DEFAULT NULL COMMENT '类型',
  `name` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '姓名',
  `sort` int(0) NOT NULL DEFAULT 0 COMMENT '顺序',
  `create_time` datetime(0) NOT NULL COMMENT '创建时间',
  `update_time` datetime(0) NOT NULL COMMENT '更新时间',
  `create_user` bigint(0) NOT NULL COMMENT '创建人',
  `update_user` bigint(0) NOT NULL COMMENT '修改人',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `idx_category_name`(`name`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin COMMENT = '菜品及套餐分类' ROW_FORMAT = Dynamic;


INSERT INTO `category` VALUES (1, 1, '张三', 1, '2022-05-27 09:16:58', '2022-07-15 20:25:23', 1, 1);
INSERT INTO `category` VALUES (2, 1, '李四', 2, '2022-05-27 09:17:07', '2022-06-02 14:27:22', 1, 1);
INSERT INTO `category` VALUES (3, 2, '王五', 3, '2022-05-27 09:17:28', '2022-07-09 14:37:13', 1, 1);
INSERT INTO `category` VALUES (4, 2, '赵六', 11, '2022-07-09 11:36:15', '2022-07-09 14:39:15', 1, 1);
INSERT INTO `category` VALUES (5, 3, '唐七', 5, '2022-07-09 11:40:30', '2022-07-09 14:43:45', 1, 1);
INSERT INTO `category` VALUES (6, 4, '范八', 12, '2022-07-09 14:30:07', '2022-07-09 14:39:19', 1, 1);
INSERT INTO `category` VALUES (7, 4, '杨九', 6, '2022-07-09 14:35:02', '2022-07-09 14:39:05', 1, 1);

SET FOREIGN_KEY_CHECKS = 1;

2.2 创建SpringBoot工程

请使用IDEA快速创建一个SpringBoot的工程,在pom.xml中导入以下依赖,

     <!--mybatis-plus依赖-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.3.1</version>
		</dependency>
 
		<!-- 代码生成器所需依赖  -->
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity-engine-core</artifactId>
			<version>2.2</version>
		</dependency>

2.3 mybatis_plus提供基础结构代码自动生成

运行以下main方法就会自动生成SpringMVC基础架构,mapper层记得加上@Mapper注解

/**
*代码自动生成类
*/

public class SggCodeGenerator {
    public static void main(String[] args) {

        // 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 2、全局配置
        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(null); //主键策略
        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
        gc.setSwagger2(true);//开启Swagger2模式

        mpg.setGlobalConfig(gc);

        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/rui?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 4、包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null); //模块名
        pc.setParent("com.example.test3");
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("category");//对那一张表生成代码
        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作

        strategy.setRestControllerStyle(true); //restful api风格控制器
        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符

        mpg.setStrategy(strategy);

        // 6、执行
        mpg.execute();
    }
}

2.4 配置数据库来源application.yml

填写基础基础用户名和密码,以及数据库名称

server:
  port: 8888
spring:
  datasource:
    username: xxx
    password: xxx
    driver-class-name: com.mysql.cj.jdbc.Driver
    #连接本地数据库
    url: jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC

mybatis-plus:
  # mapper.xml 文件扫描
  mapper-locations: classpath*:/mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true

# 日志配置
logging:
  level:
    com.xxx.xxx: debug
    org.springframework: warn



3. 开始代码编写 

3.1开始controller调用mapper层自带方法实现增删查改

1 相等判断

1.1 allEq
全部条件都相等。

Map<String,Object> map = new HashMap<>();

map.put("type",1);

map.put("name","张三");

QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.allEq(map);

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;

 
1.2 eq
指定条件相等。
 QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().eq(Category::getName,"李四");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


1.3 ne
指定条件不相等。
QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().ne(Category::getName,"李四");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;

 2 范围判断

2.1 gt
大于指定条件。

QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().gt(Category::getType,1);

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
2.2 ge
大于等于指定条件。
 QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().ge(Category::getType,2);

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
2.3 lt
小于指定条件。

QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().lt(Category::getType,2);

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
2.4 le

小于等于指定条件。
 QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().le(Category::getType,2);

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
2.5 between
介于指定范围之间。
 QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().between(Category::getType,"2","3");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
2.6 notBetween

不介于指定范围之间。
QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().notBetween(Category::getType,"2","3");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;

 3 模糊匹配

3.1 like
某个字符串包含指定字符串。
QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().like(Category::getCreateTime,"2022");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
3.2 notLike
某个字符串不包含指定字符串。
 QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().notLike(Category::getCreateTime,"14");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
3.3 likeLeft

某个字符串以指定字符串结尾。
QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().likeLeft(Category::getCreateTime,"58");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
3.4 likeRight
某个字符串以指定字符串开头。
 QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().likeRight(Category::getCreateTime,"2022");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;

4 非空判断 

4.1 isNull
指定字段为null。
QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().isNull(Category::getType);

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
4.2 isNotNull
指定字段不为null。
 QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().isNotNull(Category::getType);

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    

 5 in判断

5.1 in
满足指定条件之一。
 QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().in(Category::getType,"1","3");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
5.2 notIn
不满足指定条件之一。
QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().notIn(Category::getType,"1","3");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
5.3 inSql 
满足指定条件之一。
QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().inSql (Category::getType,"1,3");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
5.4 notInSql
不满足指定条件之一。

QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().notInSql(Category::getType,"1,3");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;

6 分组

6.1 groupBy
按字段值分组,每一组只会出现一条数据。
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().groupBy(UserEntity::getSex);
        return userService.list(queryWrapper);


7 排序

7.1 orderByAsc
根据指定字段升序排序。
QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().orderByAsc(Category::getCreateTime);

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
7.2 orderByDesc

根据指定字段降序排序。

QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().orderByDesc(Category::getCreateTime);

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


   
7.3 orderBy
根据指定字段升序/降序排序。
 QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().orderBy(true,false,Category::getCreateTime);

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;

注:

(1)第一个参数必须为true。

(2)第二个参数为true则升序排序,为false则降序排序。

 8 条件判断

8.1 having
跟sql里面的having类似。

QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.select("type,count(*) as sexCount")

.groupBy("type")

.having("count(*)>1");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;
注:

(1)having()需要配合select()、groupBy()一起配合使用。

(2)having里面只能使用聚合函数。

8.2 func
主要方便在出现if...else下调用不同方法能不断链。
 Boolean s = false;

LambdaQueryWrapper<Category> queryWrapper = Wrappers.<Category>lambdaQuery(); queryWrapper.func(x -> {

if (s) {

x.eq(Category::getType, 2);

} else {

x.eq(Category::getType, 1); } });

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;

9 逻辑判断

 9.1 and
与逻辑判断。(条件拼接)

QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().eq(Category::getName,"张三")

.and(t -> t.eq(Category::getType, "1"));

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


9.2 or
或逻辑判断。
QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.lambda().eq(Category::getName,"张三")

.or(t -> t.eq(Category::getType, "2"));

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;

10 存在判断

 10.1 exists
exists用于检查子查询是否会返回数据,该子查询实际上并不返回任何数据,有查询数据返回值为true,没有查询数据返回值为false。
 QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.exists("select * from category where name='张三'");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;


    
10.2 notExists

notExists用于检查子查询是否不会返回数据,该子查询实际上并不返回任何数据,有查询数据返回值为false,没有查询数据返回值为true。
   QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.notExists("select * from category where name='张三'");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;

 11 查询字段

11.1 select

QueryWrapper<Category> queryWrapper =new QueryWrapper<>(); queryWrapper.select("name,type");

List<Category> categories = categoryMapper.selectList(queryWrapper);

return "数据为"+ categories;

猜你喜欢

转载自blog.csdn.net/f234344435/article/details/128316808