• MyBatis-Plus 和swagger


    MyBatis-Plus

    1.1MyBatis Plus 简介

    mybatisplus 官网: https://baomidou.com/
    MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变, 为简化开发、提高效率而生。

    1.2主要特性:

    (1)提供Mapper基类接口, 可以自动完成简单的CRUD操作

    (2)提供QueryWrapper包装器,它支持类似Hibernate的Criteria的多于条件查询和排序;

    (3)提供MyBatis拦截器,能自动实现分页。

    1.3MyBatis-plus的使用

    一.创建基于springboot的项目

     <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starterartifactId>
            dependency>
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <scope>runtimescope>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <version>1.18.20version>
            dependency>
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-boot-starterartifactId>
                <version>3.4.0version>
            dependency>
            <dependency>
                <groupId>cn.hutoolgroupId>
                <artifactId>hutool-allartifactId>
                <version>5.3.9version>
            dependency>
        dependencies>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    二.配置application.yml文件

    
    spring:
      application:
        # 项目名
        name: mybatis-plus 
      datasource:
        # sql驱动
        driver-class-name: com.mysql.cj.jdbc.Driver
        #数据源 
        url: jdbc:mysql://localhost:3306/mycinema?serverTimezone=Asia/Shanghai  
        username: root
        password: hx12345678
    mybatis-plus:
      configuration:
        # 默认日志
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
        #关闭驼峰命名规则
        map-underscore-to-camel-case: false  
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    注意:MyBatis Plus默认了数据库命名使用下划线规则,实体类属性名使用了Pascal或Camel命名规范 的,切换成数据库时会自动加上下划线,如果不需要修改为下划线规则,则需要显式关闭属性

    ”map-underscore-to-camel-case: false“

    开启驼峰命名规则 则 userId 被映射为 user_id 大写字母变成 _ 加小写

    三.实体注解

    不同于MyBatis中所有SQL都需要自己编写的做法,MyBatis Plus可以根据实体类及所配置的注解, 自动生成简单CURD所的对应的SQL操作,MyBatis Plus会默认认为实体类名就是数据库表名,而实体类 的属性名就是数据库表中对应的字段名。 但这种默认关系很多时候是不成立的,当我们的类名和表名、属性名和字段名对应不上时,就需要 通过注解指定。 注解 描述 常用属性

    注解描述常用属性
    @TableName表名注解,指定实体类和数据库表的对应 关系
    @TableId主键注解,指定数据库主键的字段名、主 键生成策略value:字段名 type:主键生成策略(IdType枚 举)
    @TableField非主键字段注解value:字段名 exits:是否为数据库表字段 insertStrategy:插入策略(默 认非空) updateStrategy:更新策略
    @TableLogic逻辑删除(value=“1”,delval = “0”)删除实际上是更新操作

    四.Lombok

    lombok 提供了简单的注解的形式来帮助我们简化消除一些必须有但显得很臃肿的 java 代码,尤其是针对pojo,在 MybatisPlus中使用lombox

    1.安装idea插件-lombok

    2.常用注解

    注解作用
    @Data注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、 hashCode、toString 方法
    @Getter注解在属性上;为属性提供 getting 方法
    @Setter注解在属性上;为属性提供 setting 方法
    @Slf4j注解在类上;为类提供一个 属性名为log 的 slf4j日志对象
    @NoArgsConstructor注解在类上;为类提供一个无参的构造方法
    @AllArgsConstructor注解在类上;为类提供一个全参的构造方法
    @Builder使用Builder模式构建对象

    五.构造实体类Category

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    @TableName("category")  //指定实体类和数据库表的对应 关系
    public class Category {
    
      @TableId(type = IdType.AUTO) //数据库主键自增,保存后带回自增值
      private int id;
      private String name;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    六.构造Mapper接口

    mapper接口 MyBatis Plus 提供了 Mapper 父接口 BaseMapper,继承后可以直接获得简单的CRUD操作方法, 无需编写SQL即可完成单表对象的CURD操作。

    public interface CategoryMapper  extends BaseMapper<Category> {
    }
    
    • 1
    • 2

    测试增删改查的方法

     @SpringBootTest
    class DemoApplicationTests {
    
        @Autowired
        private CategoryMapper categoryMapper; //别忘记在 启动类扫描包@MapperScan("com.powernode.mapper")
    
        @Test
        public void getAll() {   //查询所有集合
            List<Category> categories = categoryMapper.selectList(null);
            categories.forEach(categorie -> System.out.println(categorie));
        }
    
        @Test
        public void add() {  //添加  插入 依旧输出 11,因为主键Id自增
            Category category = new Category(1, "喜剧片");
            System.out.println(categoryMapper.insert(category));
            System.out.println(category.getId());
        }
    
        @Test
        public void update() {    //更新
            Category category = new Category(1, "测试");
            categoryMapper.updateById(category);//根据ID 更新
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("name","xxx");
            categoryMapper.update(category,queryWrapper);//根据 条件跟新  where name = xxx;
        }
    
        @Test
        public void delete() {  //删除 id = 5,6
            List<Integer> list = new ArrayList<>();
            list.add(5);
            list.add(6);
            categoryMapper.deleteBatchIds(list);//批量删除
            categoryMapper.deleteById(5);  //单个删除
    
        }
    
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    1.4MyBatis Plus 实现复杂查询

    使用QueryWrapper实现多条件动态SQL查询 MyBatis Plus 提供了 QueryWrapper 对象,可以用于包装查询条件,可以灵活的为查询添加条 件。 编写一个Movie实体类:

    QueryWrapper :所有方法

    img

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    @TableName("movie")
    public class Movie {
        @TableId(type= IdType.AUTO) //数据库主键自增,保存后带回自增值
        private Integer id;
        @TableField(value = "title")//非主键字段注解  默认就是类名
        private String title;
        private String poster;
        private String director;
        private Integer categoryId;
        private Date dateReleased;
        //类别对象  非数据库列 加exist =false
        @TableField(exist = false)
        private Category category;
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    MovieMapper

    public interface MovieMapper extends BaseMapper<Movie> {
    }
    
    
    • 1
    • 2
    • 3
       /* 使用QueryWrapper实现多条件动态SQL查询 MyBatis Plus 提供了 QueryWrapper 对象,
        可以用于包装查询条件,可以灵活的为查询添加条 件。*/
        @Test //电影按类别,名称模糊查询
        public void getByCondition() {
            QueryWrapper<Movie> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("categoryId", 1);
            queryWrapper.like("title", "的");
            /*
             * ELECT *
             * FROM movie
             *  WHERE (categoryId = ? AND title LIKE ?)
             * */
            List<Movie> movies = movieMapper.selectList(queryWrapper);
            movies.forEach(movie -> System.out.println(movie));
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在这里插入图片描述

    简化 写法:

        @Test  //电影按类别,名称模糊查询  封装到一句代码
        public void getByTitleAndCategoryId() {
            List<Movie> movies = movieMapper.selectList(new QueryWrapper<Movie>()
                    .eq("categoryid", 1)
                    .like("title", "的"));
            System.out.println(movies);
        }
       
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    添加执行条件

    @Test //动态查询--查询所有,按类别,按名称,同时两个条件
        public void dynamicSelect() {
            int cid = -1;  //条件   如果cid>0则不执行这个条件
            String title = "的"; //存在   如果 title 不存在或者为空 不执行这个条件
            List<Movie> list = movieMapper.selectList(new QueryWrapper<Movie>()
                    .eq(cid > 0, "categoryid", cid)
                    .like(StringUtils.hasText(title), "title", title));
            System.out.println(list);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    使用lambda表达式LambdaQueryWrapper

       @Test   //lambda表达式LambdaQueryWrapper
        public void lambdaSelect() {
            List<Movie> list = movieMapper.selectList(new LambdaQueryWrapper<Movie>()
                    .eq(Movie::getCategoryId, 1)
                    .like(Movie::getTitle, "的"));
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
      @Test
        public  void selectAvg()
         {
           List<Integer> list=Arrays.asList(1,2,3);
           List<Movie> list1=movieMapper.selectBatchIds(list);
             System.out.println(list1.size());
         }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1.5last条件构造器

    使用QueryWrapper的 last 条件构造器可以直接把 SQL子句直接拼接到最终生成的SQL的最后,这 种做法有时非常方便。 last 条件构造器只能调用一次,多次调用以最后一次为准 有sql注入的风险,请谨慎使用。

    queryWrapper.last("limit 5, 10") 
    
    • 1
    
        @Test
        public void getTop() {
            System.out.println(movieMapper.selectList(new LambdaQueryWrapper<Movie>()
                    .eq(Movie::getCategoryId, 1)
                    .last("limit 3")   //拼接sql语句到最后,只是调用一次,多次调用以最后一次为主
    //                .last("order by id desc")
            ));
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

    1.6 SQL排序

    QueryWrapper 对象还提供了 “orderByDesc” 和 “orderByAsc” 等方法,可以简单实现排序

     @Test
    public void order()
     {
         QueryWrapper<Movie> queryWrapper=new QueryWrapper<>();
         queryWrapper.orderByDesc("dateReleased");
         queryWrapper.last("limit 6");
         List<Movie> list=movieMapper.selectList(queryWrapper);
         list.forEach(System.out::println);
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    使用lambda表达式

     @Test
        public void order() {
            movieMapper.selectList(new LambdaQueryWrapper<Movie>()
                    .eq(Movie::getCategoryId, 1)
                    .orderByDesc(Movie::getDateReleased, Movie::getId)//降序
    //                .orderByAsc(Movie::getDateReleased, Movie::getId)//降序  默认降序
    
            );
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    1.7SQL分页查询

    (1)配置分页拦截器: 在配置类(也可以是SpringBoot启动类)中声明分页拦截器Bean

     //分页拦截器  本质就是动态代理,非入侵
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor(){
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
           //告诉mybatis 是mysql 分页
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            return interceptor;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    (2)使用分页对象 IPage 控制当前页码和每页大小

    public IPage<Movie> findMoviesPage(..., int pageNum, int pageSize){
    QueryWrapper<Movie> query = new QueryWrapper<Movie>();
    ......
    Page<Movie> page = new Page<Movie>(pageNum, pageSize); //设置分页对象
    return movieDb.selectPage(page, query);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    IPage 返回对象中可以获取当前页数据实体集合 getRecords(),总行数 getTotal(),总页数 getPages(), 当前页 getCurrent(),每页大小 getSize() 等数据

    分页查询测试

     @Test
     //分页
        @Test
        public void pageTest(){
            //第二页  每页3条
            Page<Movie> page = new Page<>(2,10);
            Page<Movie>moviePage = movieMapper.selectPage(page,null);
            System.out.println("总条数"+moviePage.getTotal());
            System.out.println("总页数"+moviePage.getPages());
            System.out.println("当前页"+moviePage.getCurrent());
            System.out.println("countid"+moviePage.getCountId());
            System.out.println("最大分页条数限制"+moviePage.getMaxLimit());
            System.out.println("每页显示条数,默认 10"+moviePage.getSize());
    
            //记录数
            moviePage.getRecords().forEach(System.out::println);
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
       @Test
        public void pageTest2(){
            //第二页  每页3条
            Page<Movie> page = new Page<>(2,10);
            Page<Movie>moviePage = movieMapper.selectPage(page,new LambdaQueryWrapper<Movie>()
                    .eq(Movie::getCategoryId,1));
            System.out.println("总条数"+moviePage.getTotal());
            System.out.println("总页数"+moviePage.getPages());
            System.out.println("当前页"+moviePage.getCurrent());
            System.out.println("countid"+moviePage.getCountId());
            System.out.println("最大分页条数限制"+moviePage.getMaxLimit());
            System.out.println("每页显示条数,默认 10: "+moviePage.getSize());
    
            //记录数
            moviePage.getRecords().forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    1.8跨表查询

    多次查询实现简单的跨表查询方案 MyBatis Plus 的自动化功能基本都是针对单表的CURD操作,如果涉及到跨表查询,并没有什么简 单的自动化方案。 如果撇开多次查询和复杂连表(join)之间的性能哪个更优,我们也可以结合Java8的stream操作, 使用二次查询的方式对跨表实体数据进行查询。

    (1)在系统中添加包含外键对象的VO

    @Data
    public class MovieVO {
    private int id;
    private String title;
    private String movieCode;
    private String director;
    private Date dateReleased;
    private int categoryId;
    private Category category;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    (2)在加载时使用单独查询外键的方式加载

     @Test
        public  void getAllMovieVo()
         {
             Movie movie=movieMapper.selectById(1);
             movie.setCategoryName(categoryMapper.selectById(movie.getCategoryId()).getName());
             System.out.println(movie.getCategoryName());
             MovieVO movieVo=new MovieVO();
            //使用hutool工具类进行同名属性拷贝
             BeanUtil.copyProperties(movie,movieVo);
             movieVo.setCategory(categoryMapper.selectById(movie.getCategoryId()));
             System.out.println(movieVo);
         }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
      @Test//跨表查询 避免了多表查询
        public void setMovieCategory(){
    
            Movie movie = movieMapper.selectById(1);
    
            //查询类别
            Category category = categoryMapper.selectById(movie.getCategoryId());
            movie.setCategory(category);
            System.out.println(movie);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
     @Test
        public  void getMovieWithCategory(){
            List<Movie> movieList = movieMapper.selectList(null);
            //查一次类别
            List<Category> categoryList = categoryMapper.selectList(null);
            movieList.forEach(movie -> {
                //流式语法
                Category category = categoryList.stream()
                        //过滤
                        .filter(category1 -> category1.getId().equals(movie.getCategoryId()))
                        //装换为List集合
                        .collect(Collectors.toList())
                        //获取一个元素
                        .get(0);
                movie.setCategory(category);
                System.out.println(movie);
            });
    //
    //        for(Movie movie : movieList){
    //            for (Category category : categoryList) {
    //                if(movie.getCategoryId().equals(category.getId())){
    //                    movie.setCategory(category);
    //                    break;
    //                }
    //            }
    //        }
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    1.9MyBatis-plus代码生成器

    使用插件方式:
    在这里插入图片描述

    在这里插入图片描述
    在这里插入图片描述

    使用代码方式生成:

     <dependencies>
                
                <dependency>
                    <groupId>com.baomidougroupId>
                    <artifactId>mybatis-plus-generatorartifactId>
                    <version>3.4.0version>
                dependency>
                
                <dependency>
                    <groupId>org.freemarkergroupId>
                    <artifactId>freemarkerartifactId>
                    <version>2.3.29version>
                dependency>
                
                <dependency>
                    <groupId>com.spring4allgroupId>
                    <artifactId>spring-boot-starter-swaggerartifactId>
                    <version>1.5.1.RELEASEversion>
                dependency>
            dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    
    import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
    import com.baomidou.mybatisplus.core.toolkit.StringPool;
    import com.baomidou.mybatisplus.core.toolkit.StringUtils;
    import com.baomidou.mybatisplus.generator.AutoGenerator;
    import com.baomidou.mybatisplus.generator.InjectionConfig;
    import com.baomidou.mybatisplus.generator.config.*;
    import com.baomidou.mybatisplus.generator.config.po.TableInfo;
    import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class MyGenerator {
        /*读取控制台内容,这里暂不使用*/
        public static String scanner(String tip) {
            Scanner scanner = new Scanner(System.in);
            StringBuilder help = new StringBuilder();
            help.append("请输入" + tip + ":"); //可以输入包名:比如com.musicstore
            System.out.println(help.toString());
            if (scanner.hasNext()) {
                String ipt = scanner.next();
                if (StringUtils.isNotBlank(ipt)) {
                    return ipt;
                }
            }
            throw new MybatisPlusException("请输入正确的" + tip + "!");
        }
    
        /* 配置并执行代码生成器 */
        public static void main(String[] args) {
            // 代码生成器
            AutoGenerator mpg = new AutoGenerator();
            // 全局配置
            GlobalConfig gc = new GlobalConfig();
            String projectPath = System.getProperty("user.dir");
            gc.setOutputDir(projectPath + "/src/main/java");
            gc.setAuthor("mengyang");
            gc.setOpen(false);
            gc.setServiceName("%sService");
            //设置业务接口后缀为Biz,默认Service
            gc.setServiceImplName("%sServiceImpl");
            //设置业务实现类后缀为BizImpl,默认 ServiceImpl
            gc.setSwagger2(true); //是否为实体属性添加 Swagger2 注解
            mpg.setGlobalConfig(gc);
            // 数据源配置
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://localhost:3306/mycinema?serverTimezone=GMT%2B8");
            dsc.setSchemaName("public");
            dsc.setDriverName("com.mysql.cj.jdbc.Driver");
            dsc.setUsername("root");
            dsc.setPassword("123456");
            mpg.setDataSource(dsc);
            // 包配置
            PackageConfig pc = new PackageConfig();
            pc.setModuleName(scanner("模块名"));
            pc.setParent("com"); //设置生成代码的“父级包名”
            pc.setService("service"); //设置业务包名,默认是service
            pc.setServiceImpl("service.impl"); //设置业务实现类包名,默认service.impl
            mpg.setPackageInfo(pc); // 自定义配置
    
            InjectionConfig cfg = new InjectionConfig() {
                @Override
                public void initMap() {
                    // to do nothing
                } };
    // 设置代码模板(这里用的模板引擎是 freemarker)
            String templatePath = "/templates/mapper.xml.ftl";
            // 自定义输出配置
            List<FileOutConfig> focList = new ArrayList<>(); // 自定义配置会被优先输出
            focList.add(new FileOutConfig(templatePath) {
                @Override
                public String outputFile(TableInfo tableInfo) { // 自定义mapper xml 文件路径 ,如果你 Entity 设置了前后缀、此处注意 xml 的名 称会跟着发生变化!!
                    return projectPath + "/src/main/resources/mapper/" //+ pc.getModuleName() //mapper输出目录中加上模块名称,复杂项目才 需要
                            + "/" + tableInfo.getEntityName() + "Mapper" +
                            StringPool.DOT_XML;
                }
            });
            cfg.setFileOutConfigList(focList);
            mpg.setCfg(cfg);
            // 配置模板
            TemplateConfig templateConfig = new TemplateConfig();
            templateConfig.setXml(null);
            mpg.setTemplate(templateConfig);
            // 策略配置
            StrategyConfig strategy = new StrategyConfig();
            strategy.setNaming(NamingStrategy.underline_to_camel); //表名从下划线 转为驼峰
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);
            //字段名从下划 线转为驼峰
            strategy.setEntityLombokModel(true);
            //Entity使用 Lombok风格格式
            strategy.setRestControllerStyle(true); //控制器使用 REST风格//
            strategy.setTablePrefix("tbl_");
            //设置表名前 缀,生成代码时会“去除表前缀”
            // 设置针对哪些数据库表有效,setExclude()表示排除某些表,
            // setInclude()表示包含某些表   strategy.setExclude();
            //strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
            strategy.setControllerMappingHyphenStyle(true);
            mpg.setStrategy(strategy);
            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
            mpg.execute();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105

    https://juejin.cn/post/6844903901724950535

    2.swagger

    2.1什么是Swagger

    Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。

    2.2作用

    • 接口文档在线自动生成
    • 功能测试

    Swagger是一组开源项目,其中主要要项目如下:

    • Swagger-tools:提供各种与Swagger进行集成和交互的工具。例如模式检验、Swagger 1.2文档转换成Swagger 2.0文档等功能。
    • Swagger-core: 用于Java/Scala的的Swagger实现。与JAX-RS(Jersey、Resteasy、CXF…)、Servlets和Play框架进行集成。
    • Swagger-js: 用于JavaScript的Swagger实现。
    • Swagger-node-express: Swagger模块,用于node.js的Express web应用框架。
    • Swagger-ui:一个无依赖的HTML、JS和CSS集合,可以为Swagger兼容API动态生成优雅文档。
    • Swagger-codegen:一个模板驱动引擎,通过分析用户Swagger资源声明以各种语言生成客户端代码。

    2.3在Spring使用Swagger

    在Spring中集成Swagger会使用到springfox-swagger,它对Spring和Swagger的使用进行了整合

      <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger2artifactId>
                <version>2.9.0version>
            dependency>
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger-uiartifactId>
                <version>2.9.0version>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2.4配置Swagger

    @Configuration
    public class SwaggerConfig {
        /**
         * 创建API应用
         * apiInfo() 增加API相关信息
         * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
         * 本例采用指定扫描的包路径来定义指定要建立API的目录。
         * @return
         */
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.musicstore"))
                    .paths(PathSelectors.any())
                    .build();
    
        }
        /**
         * 创建该API的基本信息(这些基本信息会展现在文档页面中)
         * 访问地址:http://项目实际地址/swagger-ui.html
         * @return
         */
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("Swagger2构建RestFul的API")
                    .description("swagger生成规范的api文档,便于前后端交互")
                    .termsOfServiceUrl("")
                    .contact(new Contact("mengyang","http://www.mengyang.com","mengyang@163.com"))
                    .version("1.0")
                    .build();
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    2.5常用注解

    描述注解
    @Api用在类上,该注解将一个Controller(Class)标注为一个swagger资源(API)
    @ApiOperation一个操作或HTTP方法进行描述
    @ApiModel描述一个Model的信息
    @ApiModelProperty

    2.6配置application.properties

    spring.mvc.pathmatch.matching-strategy=ant_path_matcher
    
    • 1

    2.7配置启动类

    @SpringBootApplication
    @MapperScan("com.musicstore.mapper")
    @EnableSwagger2
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2.8启动测试

    浏览器输入:http://localhost:8080/swagger-ui.html

  • 相关阅读:
    MFC中对编码文件的操作01
    [云原生]微服务架构是什么?
    Ubuntu,Windows下编译MNN的推理和模型转化工具
    安卓手机应用开发需要学什么专业知识呢?
    使用C语言实现链队(带头结点和不带头结点)
    【教程】Autojs使用OpenCV进行SIFT/BRISK等算法进行图像匹配
    表单设计中,印刷模式和拖拽模式选哪个?成年人:全都要
    【C++ • STL】探究string的源码
    接口interface
    C#和Java,究竟选哪个方向?我只说事实,你自己分析……
  • 原文地址:https://blog.csdn.net/qq_51307593/article/details/128001352