栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot-mybatisplus笔记

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot-mybatisplus笔记

1,课程回顾 2,本章重点
 mybatisplus   简介  特点

 mybatisplus  入门例子

 springboot整合mybatisplus及使用

 mybatisplus 自动代码生成

 mybatisplus 分页插件

 hutool  工具包

 easycode代码生成springboot+mybatisplus    
3,具体内容 3.1 mybatisplus 简介 特征 3.1.1 简介:
      为简化开发而生,简化mybatis单表CRUD过程,只做增强不做改变,自动代码生成,自动分页。

   MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
3.1.2 特征:
  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
3.2 框架架构


3.3 mybatisplus 入门例子
3.3.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)
);

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');

3.3.2 创建工程引入jar
引入parent


  org.springframework.boot
  spring-boot-starter-parent
  2.6.2
  

  引入其他依赖:     
 
      org.springframework.boot
      spring-boot-starter
    
    
      org.springframework.boot
      spring-boot-starter-test
      test
    
    
    
      com.baomidou
      mybatis-plus-boot-starter
      3.5.0
    
    
    
      mysql
      mysql-connector-java
      5.1.49
    

    
    
      org.projectlombok
      lombok
      1.18.22
      provided
    

3.3.3 编写application.yml配置(注意自己的数据库版本和用户名密码)

DataSource Config
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
   # schema: classpath:db/schema-h2.sql
   # data: classpath:db/data-h2.sql
    url: jdbc:mysql://localhost:3306/db_qy141?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
#配置日志输出
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

如果使用druid可以加上jar,更换配置
 
      com.alibaba
      druid-spring-boot-starter
      1.2.8
    

#配置整合druid
spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/db_qy141?useUnicode=true&characterEncoding=utf-8
      username: root
      password: root
      initial-size: 5
      max-active: 20
      min-idle: 10
      max-wait: 10
      #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000

3.3.4 编写实体类

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

3.3.5 编写mapper

public interface UserMapper extends BaseMapper {
}

3.3.6 编写启动类

@SpringBootApplication
@MapperScan("com.aaa.sbmp.mapper")
@EnableSwagger2
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

3.3.6 编写测试类(注意测试类和启动类需要包名称一致)

@SpringBootTest
public class SampleTest {
    @Resource
    private UserMapper userMapper;
    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List userList = userMapper.selectList(null);
        //断言  不空继续  为空不再执行
        Assert.notNull(userList,"userList为空");
        //jdk8新特性   System.out::println      执行类::方法
        userList.forEach(System.out::println);
    }
}

3.4 mybatisplus 自动代码生成
3.4.1 引入jar

 
    
      com.baomidou
      mybatis-plus-generator
      3.5.1
    
    
    
      org.apache.velocity
      velocity-engine-core
      2.3
    

3.4.2 生成器代码

public class AutoCodeGenerator {
    public static void main(String[] args) {
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/db_qy141",
                "root", "root")
                .globalConfig(builder -> {//全局配置
                    builder.author("baomidou") // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("D:\idea_qy141\springboot_mybatisplus_demo_20220114\src\main\java"); // 指定输出目录
                })
                .packageConfig(builder -> {//包配置
                    builder.parent("com.aaa") // 设置父包名
                            .moduleName("sbmp") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml,
                                    "D:\idea_qy141\springboot_mybatisplus_demo_20220114\src\main\resources\mapper")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("tb_dept","sys_menu") // 设置需要生成的表名
                            .addTablePrefix("tb_", "sys_"); // 设置过滤表前缀
                })
                //.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
    }
}

3.5 springboot整合mybatisplus及使用
3.5.1 学习mybatisplus提供的service和dao接口
https://baomidou.com/pages/49cc81/
3.5.2 配置mybatisplus 分页插件

@Configuration
public class MybatisPlusConfig {
    
    @Bean // 

3.5.3 编写分页带参查询代码,学习QueryWrapper用法:
QueryWrapper用法:https://baomidou.com/pages/10c804/

@Service
public class DeptServiceImpl extends ServiceImpl implements IDeptService {

    @Resource
    private DeptMapper deptMapper;
    @Override
    public IPage queryPage(Map map) {
        //分页参数设置
        IPage  page = new Page<>();
        //设置当前页码  第几页
        page.setCurrent(Long.valueOf(map.get("pageNo")+""));
        //设置每页显示条数
        page.setSize(Long.valueOf(map.get("pageSize")+""));
        //查询封装类
        QueryWrapper queryWrapper =new QueryWrapper();
        //使用加各种参数
       // if(map.get("deptName")!=null&&!map.get("deptName").equals("")){
        if(!StringUtils.isEmpty(map.get("deptName"))){
            queryWrapper.like("dname",map.get("deptName"));
        }
        if(!StringUtils.isEmpty(map.get("loc"))){
            queryWrapper.like("loc",map.get("loc"));
        }
        return deptMapper.selectPage(page,queryWrapper);
    }
}

3.5.4 编写controller代码

@RestController
@RequestMapping("/sbmp/dept")
public class DeptController extends BaseController{
    @Resource
    private IDeptService iDeptService;
    
    @PostMapping("add")
    public Result  add(@RequestBody Dept dept){
        return success(iDeptService.save(dept));
    }
    
    @PutMapping("update")
    public Result  update(@RequestBody Dept dept){
        return success(iDeptService.saveOrUpdate(dept));
    }
    
    @DeleteMapping("removeById")
    public Result  removeById(Integer depNo){
        return success(iDeptService.removeById(depNo));
    }

    
    @PutMapping("page")
    public Result  page(@RequestBody Map  map){
        return success(iDeptService.queryPage(map));
    }
}

3.5.5 整合swagger及测试
引入swagger包
注意:最新版本spring-boot 3.6.2整合swagger任何版本都会报空指针,降低springboot版本为3.5.7


  io.springfox
  springfox-swagger2
  2.9.2



  io.springfox
  springfox-swagger-ui
  2.9.2

swagger配置

@Configuration
public class SwaggerConfig {
    
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //.enable(false)  //swagger不能访问
                .select()
                //配置要扫描接口的方式
                .apis(RequestHandlerSelectors.basePackage("com.aaa.sbmp.controller"))
                //路径过滤
                .paths(PathSelectors.any())
                .build();
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建springboot+mybatisplus")
                .description("更多请关注http://www.baidu.com")
                .termsOfServiceUrl("http://www.baidu.com")
                .contact(new Contact("AAA","http://www.baidu.com","123@qq.com"))
                .version("1.0")
                .build();
    }
}

启动类加入注解
@EnableSwagger2
version:1.0.0

 */
@SpringBootApplication
@MapperScan("com.aaa.sbmp.mapper")
@EnableSwagger2
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

3.5.6 启动测试:
http://localhost:8080/swagger-ui.html
3.6 hutool 工具包
简介:
Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。

Hutool中的工具方法来自每个用户的精雕细琢,它涵盖了Java开发底层代码中的方方面面,它既是大型项目开发中解决小问题的利器,也是小型项目中的效率担当;

Hutool是项目中“util”包友好的替代,它节省了开发人员对项目中公用类和公用工具方法的封装时间,使开发专注于业务,同时可以最大限度的避免封装不完善带来的bug。
引入和使用:

cn.hutool
hutool-all
5.7.19

if(StrUtil.isNotEmpty(map.get(“deptName”))){
queryWrapper.like(“dname”,map.get(“deptName”));
}
if(StrUtil.isNotEmpty(map.get(“loc”))){
queryWrapper.like(“loc”,map.get(“loc”));
}

3.7 QueryWrapper的使用

QueryWrapper queryWrapper =new QueryWrapper();
        Map map =new HashMap();
        //allEq的用法
        
     
        //eq用法
        //queryWrapper.eq("deptno",dept.getDeptno());
        //queryWrapper.eq(dept.getDeptno()>0,"deptno",dept.getDeptno());
        //ne用法
        //queryWrapper.ne("deptno",dept.getDeptno());
        //queryWrapper.ne(dept.getDeptno()>0,"deptno",dept.getDeptno());
        //gt
        //queryWrapper.gt("deptno",dept.getDeptno());
        //ge
        //queryWrapper.gt("deptno",dept.getDeptno());
        //between   notBetween用法
       // queryWrapper.between("deptno",dept.getMinValue(),dept.getMaxValue());
       // queryWrapper.between(dept.getMinValue()>0&&dept.getMaxValue()>0,"deptno",dept.getMinValue(),dept.getMaxValue());
        //like notLike 用法  likeLeft likeRight
       // queryWrapper.notLike("dname",dept.getDname());
       // queryWrapper.notLike(dept.getDname()!=null,"dname",dept.getDname());
        // isNull用法   isNotNull
       // queryWrapper.isNull("dname");
        //queryWrapper.isNull("loc");
        //queryWrapper.isNotNull("dname");
        // in  notIn用法
       // queryWrapper.in("deptno",55,60,70);
       
        //queryWrapper.in("deptno",Arrays.asList(dept.getDname().split(",")));
        //insql 用法  sql嵌套子查询   notInSql
       //queryWrapper.inSql("deptno",dept.getSql());
      // queryWrapper.inSql(dept.getSql()!=null,"deptno",dept.getSql());
       //queryWrapper.notInSql("deptno",dept.getSql());
        //groupBy
        //queryWrapper.groupBy("dname");
        //orderByAsc  orderByDesc
        //queryWrapper.orderByAsc("deptno","dname");
        //queryWrapper.orderByDesc("deptno","dname");
       // queryWrapper.orderByDesc("dname","loc");
        //orderBy
        //queryWrapper.orderBy(dept.getDname()!=null,false,dept.getDname());
        //func 用法  有问题
       

       //or
        
        //or(Consumer)
       
       
       //nested用法
       
       //apply用法
        //--  把时间转为字符串
        //queryWrapper.apply("deptno=55");
        //queryWrapper.apply("date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'");
       // queryWrapper.apply("date_format(dateColumn,'%Y-%m-%d') = {0}","2888-08-08");
      //last用法
        //把语句后面最终都要拼接上limit 2
        //queryWrapper.last("limit 2");
        //exist
        //queryWrapper.exists("select deptno from tb_dept where deptno=55");
        //queryWrapper.exists("select deptno from tb_dept where deptno=1");
        //select  有问题
       // queryWrapper.select("dname","loc");
      
        return deptMapper.selectList(queryWrapper);

3.7 easycode代码生成springboot+mybatisplus

4,知识点总结
其他错误解决:
NoClassDefFoundError: org/apache/velocity/context/Context 异常解决,添加jar:


      org.apache.velocity
      velocity-engine-core
      2.3
    

com.baomidou.mybatisplus.extension.api.R找不到,引入包(3.4.2过时):

 
      com.baomidou
      mybatis-plus-extension
      3.4.0
    

5,本章面试题

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/821763.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号