SpringBoot项目中MybatisPlus的使用

SpringBoot项目中MybatisPlus的使用

本文主要内容:

  • 自动生成代码

  • CURD


本文在上一篇基础上做修改:使用IDEA创建一个SpringBoot项目
https://blog.csdn.net/litte_frog/article/details/82666185
使用的是springboot2.0.4版本

一、自动生成代码

目前mp更新到3.0,本文都是参考官网文档
传送门:http://mp.baomidou.com/guide/quick-start.html

1、添加依赖,在pom文件中添加以下依赖:

<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <optional>trueoptional>
dependency>

<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-boot-starterartifactId>
    <version>3.0.1version>
dependency>

2、创建生成代码的类CodeGenerator,根据自己的需求修改配置策略等

public class CodeGenerator {

    /**
     * 

* 读取控制台内容 *

*/
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("Auto-CodeGenerator"); gc.setOpen(false); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/frog?useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); //pc.setModuleName(scanner("模块名")); pc.setParent("com.frog.mybatisplus"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; List focList = new ArrayList<>(); focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称 if (pc.getModuleName() == null) { return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } else { return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); mpg.setTemplate(new TemplateConfig().setXml(null)); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); //strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity"); //strategy.setEntityLombokModel(false); //strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); strategy.setInclude(scanner("表名")); //strategy.setSuperEntityColumns("id"); strategy.setControllerMappingHyphenStyle(true); //strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }

3、执行main方法,在控制台输入表名(模块名),执行完毕后查看项目结构
SpringBoot项目中MybatisPlus的使用_第1张图片
项目结构
SpringBoot项目中MybatisPlus的使用_第2张图片

二、简单的CURD

接下来做一个最简单的CURD
1、在启动类上添加MapperScan注解值为自己mapper类存放的路径,不然启动会报错

@SpringBootApplication
@MapperScan("com.frog.mybatisplus.mapper")
public class MybatisPlusApplication {

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

2、打开生成的Controller写几个测试接口

/**
 * 

* 前端控制器 *

* * @author Auto-CodeGenerator * @since 2018-09-13 */
@RestController @RequestMapping("/frog-test") public class FrogTestController { @Autowired private IFrogTestService frogTestService; /** * 查询 * @return */ @RequestMapping( value = "selectAll", method = RequestMethod.GET) public List selectList() { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.orderByDesc("date"); return frogTestService.list(queryWrapper); } /** * 添加 * @return */ @RequestMapping( value = "insert", method = RequestMethod.POST) public Boolean insert(@RequestBody FrogTest entity) { return frogTestService.save(entity); } }

将@Controller该为@RestController,因为以接口方式测试:
3、启动项目并打开PostMan测试
SpringBoot项目中MybatisPlus的使用_第3张图片
SpringBoot项目中MybatisPlus的使用_第4张图片
这里写图片描述
测试成功
4、MP的通用CURD方法
使用代码生成器生成的service都会继承IService这个类,这个类提供很多常用的方法,我们可以直接使用,方便很多。
SpringBoot项目中MybatisPlus的使用_第5张图片

生成的mapper都继承BaseMapper这个类:
SpringBoot项目中MybatisPlus的使用_第6张图片

5、自定义sql
如果我们有业务需要编写复杂的sql,也可以编写自定义sql。首先在mapper类中添加方法:

public interface FrogTestMapper extends BaseMapper<FrogTest> {

    /**
     * 自定义修改的sql
     * @param entity
     * @return
     */
    Boolean updateMy (FrogTest entity);

}

在xml中编写自定义sql:
这里写图片描述

"updateMy" parameterType="com.frog.mybatisplus.entity.FrogTest">
       UPDATE frog_test t SET t.state = '1' WHERE t.name = #{name}

controller中调用该方法:

    @Autowired
    private FrogTestMapper mapper;

    /**
     * 修改:使用自己写的sql
     * @return
     */
    @RequestMapping(
            value = "update",
            method = RequestMethod.POST)
    public Boolean update(@RequestBody FrogTest entity) {
        return mapper.updateMy(entity);
    }

测试报错
SpringBoot项目中MybatisPlus的使用_第7张图片
根据提示我们需要配置,能扫描到mapper.xml文件,在application.yml文件中增加如下配置:

mybatis-plus:
  mapper-locations: classpath*:mapper/*.xml
  type-aliases-package: com.frog.mybatisplus.entity
  check-config-location: true
  executor-type: simple
  global-config:
      refresh: true

含义分别为:
config-location:
MyBatis Mapper 所对应的 XML 文件位置,如果您在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。
type-aliases-package:
MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML 文件中可以直接使用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含包名)。
check-config-location:
启动时是否检查 MyBatis XML 文件的存在,默认不检查。
executor-type:
通过该属性可指定 MyBatis 的执行器,MyBatis 的执行器总共有三种:
ExecutorType.SIMPLE:该执行器类型不做特殊的事情,为每个语句的执行创建一个新的预处理语句(PreparedStatement)
ExecutorType.REUSE:该执行器类型会复用预处理语句(PreparedStatement)
ExecutorType.BATCH:该执行器类型会批量执行所有的更新语句
refresh:
是否自动刷新 Mapper 对应的 XML 文件,默认不自动刷新。如果配置了该属性,Mapper 对应的 XML 文件会自动刷新,更改 XML 文件后,无需再次重启工程,由此节省大量时间。


再次启动测试,成功!

你可能感兴趣的:(SpringBoot,MybatisPlus)