springboot和mybatisplus

本文介绍了SpringBoot框架的使用,包括其快速开发特性、优点与缺点,以及如何与MyBatis整合并利用Swagger生成API文档。还讲解了MyBatisPlus的代码生成器和基本CRUD操作实例。
摘要由CSDN通过智能技术生成

一、springboot

1.springboot是什么

        Spring Boot 是一个用于简化创建和开发独立、生产级别的 Spring 应用程序的框架。它是基于 Spring 框架的,并提供了一种快速、灵活的方式来构建应用程序。

2.springboot的优缺点

        优点:易于开发、快速整合第三方框架、易于维护、降低了开发成本、高扩展性、提供了丰富的插件和工具

        缺点:系统复杂性、依赖冲突、

3.springboot的特点

        快速构建项目

        嵌入式web容器

        自动化配置

        起步依赖

        集成了大量框架

        独立运行

4.代码实现

        4.1. 创建maven工程
        4.2.引入依赖
<!--        spring web 相关-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        4.3.编写引导类
package com.cqie;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.cqie.mapper")
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
        4.4.写Controller
@RestController
public class HelloController {
    @RequestMapping("hello")
    private String hello(){
        return "hello  springboot";
    }
        4.5.application.properties配置文件

        4.6.测试

5.SpringBoot整合Mybatis合成Swagger

        5.1.添加相关依赖
        <properties>
        <swagger.version>3.0.0</swagger.version>
        </properties>
        <!--        spring test 相关-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        5.2.配置properties

        5.3.在config包下添加Swagger配置类
package com.cqgcxy.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

// 表明当前类是配置类
@Configuration
@EnableOpenApi
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // 为api选择启动生成器
                .select()
                // 指定要生成api文档的根包
                .apis(RequestHandlerSelectors.basePackage("com.cqie.controller"))
                // 路径配置
                .paths(PathSelectors.any())
                .build();
    }
    /**
     * 创建一个ApiInfo对象
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 文档标题
                .title("农牧慧智慧养殖系统接口")
                // 简介
                .description("后端框架综合开发技术与应用课程案例")
                // 作者信息:作者姓名、作者地址、作者邮箱
                .contact(new Contact("", "http://www.baidu.com", ""))
                // 版本号
                .version("1.0")
                .build();
    }
}
        5.4.更换ui
添加依赖
<dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
        5.5.启动项目,访问http://localhost:2699/doc.html

        5.6.创建结果返回相关的两个类
        5.7.在controller包下创建类Controller

ps:swagger依赖冲突解决办法
1.在yml配置文件中添加
spring:
   mvc:
    path match:
      matching-strategy: ant_path_matcher #解决SpringBoot和Swagger2版本冲突
2.添加以下依赖
<dependency>
            <groupId>org.springframework.plugin</groupId>
            <artifactId>spring-plugin-core</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

二、mybatisplus代码生成器

1.是什么

        MyBatis Plus 是 MyBatis 的增强工具,它简化了 MyBatis 的开发流程并提供了丰富的功能扩展

2.优点

        简化开发、提供丰富的功能扩展

2.导入依赖

<properties>
        <mybatis-plus-generator.version>3.4.1</mybatis-plus-generator.version>
        <velocity-engine-core.version>2.3</velocity-engine-core.version>
    </properties>

        <!--        逆向工程代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>${mybatis-plus-generator.version}</version>
        </dependency>
        <!--        生成器默认模板引擎-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>${velocity-engine-core.version}</version>
        </dependency>    

3.在启动引导类同包下创建代码生成器类CodeGenerator

public class CodeGenerator {
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(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("");
        gc.setOpen(false);
        // 设置名字
        gc.setControllerName("%sController");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        // 设置 resultMap
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/gcxy_teach?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("");
        dsc.setPassword("");
        mpg.setDataSource(dsc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        // 包配置
        PackageConfig pc = new PackageConfig();
        //  pc.setModuleName(scanner("模块名"));
        pc.setParent("com.cqgcxy");
        mpg.setPackageInfo(pc);
        // 如果模板引擎是 velocity
        String templatePath = "/templates/mapper.xml.vm";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + 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);
        strategy.setRestControllerStyle(true);
        // 写于父类中的公共字段
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new VelocityTemplateEngine());
        mpg.execute();
    }
}

启动CodeGenerator类中的main方法,根据控制台提示输入要处理表格的名字。成功生成后找到mapper包下的接口,在其加上@Mapper

4.Mybatis-plus标准CRUD

@RestController
@Api(value = "积分等级管理",tags = {"人员信息"})
public class AccountInfoController {
    @Autowired
    private AccountInfoService accountInfoService;

    @GetMapping("/selectAll")
    @ApiOperation("查询所有人员信息")
    public R<List<AccountInfo>> selectAll(){
        List<AccountInfo> accountInfos = accountInfoService.list();
        List<AccountInfoVo> accountInfoVoList = new ArrayList<>();
        accountInfos.forEach(s->{
            AccountInfoVo accountInfoVo = new AccountInfoVo();
            accountInfoVo.setUserName(s.getUsername());
            accountInfoVo.setAccount(s.getAccount());
            accountInfoVoList.add(accountInfoVo);
        });
        return R.Success(accountInfoVoList);
    }

    @PostMapping("/insertAccountInfo")
    @ApiOperation("新增人员信息")
    public R insertAccountInfo(@RequestBody AccountInfo accountInfo){
        accountInfoService.save(accountInfo);
        return R.Success();
    }
}

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值