Springboot2.0.4整合Mybatis-plus

简介

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

官方网站https://mp.baomidou.com/

本人使用Mybatis-plus也有两年了,从最早的1版本到现在都出3版本了,确实很好用。最近很多人问我怎么用,我也来分享一下使用心得。

下面介绍一下步骤:

导入依赖

主要引入数据库、连接池、以及一些项目常用的依赖,当然mybatis-plus-boot-starter少不了,我用的springboot版本是2.0.4.RELEASE

<!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!--            屏蔽tomcat-->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--引入undertow服务器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
        <!--数据库连接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.2</version>
        </dependency>
        <!--数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>
        <!-- httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <!-- json工具-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20140107</version>
        </dependency>
        <!-- redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <!-- 二维码-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- mongoDB-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <!--poi-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

配置YML

主要是数据库的配置,附带了数据库的连接池配置,Mybatis-Plus的配置,还有一些本人项目常用的配置一块放上去了

server:
  port: 8778

spring:
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    jdbc-url: jdbc:mysql://192.168.222.154:3306/dm?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&characterEncoding=utf-8
    username: username
    password: password
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20
  redis:
    host: 192.104.203.192
    port: 6380
    password: xatgood
    database: 1
    timeout: 2000ms  # 连接超时时间(毫秒)默认是2000ms
    lettuce:
      pool:
        max-active: 200  # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 100 # 连接池中的最大空闲连接
        min-idle: 50 # 连接池中的最小空闲连接
      shutdown-timeout: 100ms
  #    sentinel:  # 哨兵模式
  #      master: mymaster
  #      nodes: 192.168.222.155:26379,192.168.222.155:26380,192.168.222.155:26381
  data:
    mongodb:
      uri: mongodb://username:password@47.116.13.18:27017/dm
  servlet:
    multipart:
      # 启用
      enabled: true
      # 上传文件单个限制
      max-file-size: 100MB
      # 总限制
      max-request-size: 100MB

mybatis-plus:
  mapper-locations: classpath*:/mapper/*Mapper.xml
  type-aliases-package: com.zdyl.devicemanagement.entity
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 3
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
    #序列接口实现类配置
    #key-generator: com.baomidou.springboot.xxx
    #逻辑删除配置
    #logic-delete-value: 0
    #logic-not-delete-value: 1
    #自定义填充策略接口实现
    #meta-object-handler: com.baomidou.springboot.xxx
    #自定义SQL注入器
    #sql-injector: com.baomidou.springboot.xxx
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false

webserverconfig:
  uploadFileLocation: D:/WebSite/zdyl/web/
  picpath: D:/devicemanagement/picture/
  #uploadFileLocation: /mnt/zdyl/devicemanagement/test/uploadfile/
  ftpusername: root
  ftppassword: zdyl001
  choodediviceMGDB: jk
  equipmentalarmMGDB: ActiveAlarm

logging:
  level:
    root: info
    com.zdyl.devicemanagement.mapper: debug
    org.springframework.data.mongodb.core.MongoTemplate: DEBUG #配置MongoTemplate日志
  path: logs/
  file: devicemanagement.log
配置MybatisConfig
注入数据库配置和分页插件
*
@MapperScan("com.zdyl.devicemanagement.**.mapper")扫描mapper层也就是Dao层

@MapperScan("com.zdyl.devicemanagement.**.mapper")
@Configuration
public class MybatisConfig {

    /**
     * 数据源配置
     *
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * mybatis-plus分页插件<br>
     * 文档:http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}
最后再附带两个代码生成器---一个mysql的一个sqlserver的
引入依赖
<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
            <version>6.2.2.jre8</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

        <!-- 模板引擎mybaties-plus  代码生成 -->

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>

代码生成器---mysql

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

public class MpGenerator {
    /**
     * 项目包名
     */
    private static final String PACKAGE_NAME = "com.zdyl.devicemanagement";

    /**
     * 代码生成路径
     */
    private static final String OUTPUT_DIR = "D:\\\\mybatis\\\\test";

    /**
     * 代码注释作者
     */
    private static final String AUTHOR = "zjf";

    private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
    private static final String HOST = "192.168.222.154";
    private static final String PORT = "3306";
    /**
     * 数据库信息
     */
    private static final String DATABASE = "dm";
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    private static final String URL = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DATABASE
            + "?characterEncoding=UTF8&serverTimezone=UTC";
    /**
     * 需要生成的表
     */
    private static final String[] TABLE = new String[]{"dm_stationgroup"};

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        mpg.setGlobalConfig(buildGlobalConfig());
        // 数据源配置
        mpg.setDataSource(buildDataSourceConfig());
        // 包配置
        mpg.setPackageInfo(buildPackageConfig());
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        mpg.setCfg(cfg);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        //不生成mapper xml文件
        //templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        // 策略配置
        mpg.setStrategy(buildStrategyConfig());
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

    /**
     * 全局构造配置类
     *
     * @return
     */
    private static GlobalConfig buildGlobalConfig() {
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        //项目所在地址
        gc.setOutputDir(OUTPUT_DIR);
        //注释作者
        gc.setAuthor(AUTHOR);
        //生成文件不打开
        gc.setOpen(true);
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        // XML 二级缓存
        gc.setEnableCache(false);
        //生成result map
        // XML ResultMap
        gc.setBaseResultMap(true);
        //生成java mysql字段映射
        // XML columList
        gc.setBaseColumnList(true);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        return gc;
    }

    /**
     * 数据库配置信息
     *
     * @return
     */
    private static DataSourceConfig buildDataSourceConfig() {
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(URL);
        // dsc.setSchemaName("public");
        dsc.setDriverName(DRIVER_NAME);
        dsc.setUsername(USERNAME);
        dsc.setPassword(PASSWORD);
        dsc.setTypeConvert(new MySqlTypeConvert() {
            @Override
            public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                //将数据库中timestamp转换成date
                if (fieldType.toLowerCase().contains("datetime")) {
                    return DbColumnType.DATE;
                }
                if (fieldType.toLowerCase().contains("timestamp")) {
                    return DbColumnType.DATE;
                }
                if (fieldType.toLowerCase().contains("boolean")) {
                    return DbColumnType.BOOLEAN;
                }
                return (DbColumnType) super.processTypeConvert(globalConfig, fieldType);
            }
        });
        return dsc;
    }

    private static PackageConfig buildPackageConfig() {
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        pc.setParent(PACKAGE_NAME);
        pc.setEntity("entity");
//        pc.setXml("mapperxml");
////        pc.setMapper("mapper");
        pc.setController("controller");
        pc.setService("service");
        return pc;
    }

    private static StrategyConfig buildStrategyConfig() {
        StrategyConfig strategy = new StrategyConfig();
        // 命名规则
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setInclude(TABLE);   // 需要生成的表
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        // 默认生成的po类不继承,手动修改继承
        //strategy.setSuperEntityClass((String) null);
        // 实体是否使用Lombok插件
        strategy.setEntityLombokModel(true);
        strategy.setEntityBuilderModel(true);
//        // 自定义 service 父类
//        strategy.setSuperServiceClass("com.zdyl.devicemanagement.BaseService");
//        // 自定义 service 实现类父类
//        strategy.setSuperServiceImplClass("com.zdyl.devicemanagement.BaseServiceImpl");
        // 控制层是否使用Rest风格
        strategy.setRestControllerStyle(true);
        return strategy;
    }
}

代码生成器---sqlserver

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

public class SqlGenerator {
    /**
     * 项目包名
     */
    private static final String PACKAGE_NAME = "com.zdyl.generalpositivebuttjoint";

    /**
     * 代码生成路径
     */
    private static final String OUTPUT_DIR = "D:\\\\mybatis\\\\joint";

    /**
     * 代码注释作者
     */
    private static final String AUTHOR = "zjf";

    private static final String DRIVER_NAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private static final String HOST = "192.168.222.154";
    private static final String PORT = "1433";
    /**
     * 数据库信息
     */
    private static final String DATABASE = "db";
    private static final String USERNAME = "uername";
    private static final String PASSWORD = "password";
    private static final String URL = "jdbc:sqlserver://" + HOST + ":" + PORT + ";DatabaseName=" + DATABASE;

    /**
     * 需要生成的表
     */
    private static final String[] TABLE = new String[]{"dynamicrouting_station_notify"};

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        mpg.setGlobalConfig(buildGlobalConfig());
        // 数据源配置
        mpg.setDataSource(buildDataSourceConfig());
        // 包配置
        mpg.setPackageInfo(buildPackageConfig());
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        mpg.setCfg(cfg);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        //不生成mapper xml文件
        //templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        // 策略配置
        mpg.setStrategy(buildStrategyConfig());
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

    /**
     * 全局构造配置类
     *
     * @return
     */
    private static GlobalConfig buildGlobalConfig() {
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        //项目所在地址
        gc.setOutputDir(OUTPUT_DIR);
        //注释作者
        gc.setAuthor(AUTHOR);
        //生成文件不打开
        gc.setOpen(true);
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        // XML 二级缓存
        gc.setEnableCache(false);
        //生成result map
        // XML ResultMap
        gc.setBaseResultMap(true);
        //生成java mysql字段映射
        // XML columList
        gc.setBaseColumnList(true);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        return gc;
    }

    /**
     * 数据库配置信息
     *
     * @return
     */
    private static DataSourceConfig buildDataSourceConfig() {
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(URL);
        // dsc.setSchemaName("public");
        dsc.setDriverName(DRIVER_NAME);
        dsc.setUsername(USERNAME);
        dsc.setPassword(PASSWORD);
        dsc.setTypeConvert(new MySqlTypeConvert() {
            @Override
            public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                //将数据库中timestamp转换成date
                if (fieldType.toLowerCase().contains("datetime")) {
                    return DbColumnType.DATE;
                }
                if (fieldType.toLowerCase().contains("timestamp")) {
                    return DbColumnType.DATE;
                }
                if (fieldType.toLowerCase().contains("boolean")) {
                    return DbColumnType.BOOLEAN;
                }
                return (DbColumnType) super.processTypeConvert(globalConfig, fieldType);
            }
        });
        return dsc;
    }

    private static PackageConfig buildPackageConfig() {
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        pc.setParent(PACKAGE_NAME);
        pc.setEntity("entity");
//        pc.setXml("mapperxml");
////        pc.setMapper("mapper");
        pc.setController("controller");
        pc.setService("service");
        return pc;
    }

    private static StrategyConfig buildStrategyConfig() {
        StrategyConfig strategy = new StrategyConfig();
        // 命名规则
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setInclude(TABLE);   // 需要生成的表
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        // 默认生成的po类不继承,手动修改继承
        //strategy.setSuperEntityClass((String) null);
        // 实体是否使用Lombok插件
        strategy.setEntityLombokModel(true);
        strategy.setEntityBuilderModel(true);
//        // 自定义 service 父类
//        strategy.setSuperServiceClass("com.zdyl.devicemanagement.BaseService");
//        // 自定义 service 实现类父类
//        strategy.setSuperServiceImplClass("com.zdyl.devicemanagement.BaseServiceImpl");
        // 控制层是否使用Rest风格
        strategy.setRestControllerStyle(true);
        return strategy;
    }
}

最后分享个常用的分页工具:

public class ListPageUtil<T> {
    /**
     * 原集合
     */
    private List<T> data;

    /**
     * 上一页
     */
    private int lastPage;

    /**
     * 当前页
     */
    private int nowPage;

    /**
     * 下一页
     */
    private int nextPage;
//    
    /**
     * 每页条数
     */
    private int pageSize;

    /**
     * 总页数
     */
    private int totalPage;

    /**
     * 总数据条数
     */
    private int totalCount;

    @SuppressWarnings("unchecked")
    public ListPageUtil(List<Map<String, Object>> list, int nowPage, int pageSize) {
        if (list == null || list.isEmpty()) {
            throw new IllegalArgumentException("data must be not empty!");
        }

        this.data = (List<T>) list;
        this.pageSize = pageSize;
        /*this.totalPage = data.size()/pageSize;
        if(data.size()%pageSize!=0){
            this.totalPage++;
        }*/

        this.nowPage = nowPage;
        this.totalCount = list.size();
        this.totalPage = (totalCount + pageSize - 1) / pageSize;
        this.lastPage = nowPage - 1 > 1 ? nowPage - 1 : 1;
        this.nextPage = nowPage >= totalPage ? totalPage : nowPage + 1;

    }

    /**
     * 得到分页后的数据
     *
     * @param pageNum 页码
     * @return 分页后结果
     */
    public List<T> getPagedList() {
        int fromIndex = (nowPage - 1) * pageSize;
        if (fromIndex >= data.size()) {
            return Collections.emptyList();//空数组
        }
        if (fromIndex < 0) {
            return Collections.emptyList();//空数组
        }
        int toIndex = nowPage * pageSize;
        if (toIndex >= data.size()) {
            toIndex = data.size();
        }
        return data.subList(fromIndex, toIndex);
    }

    public int getPageSize() {
        return pageSize;
    }

    public List<T> getData() {
        return data;
    }

    public int getLastPage() {
        return lastPage;
    }

    public int getNowPage() {
        return nowPage;
    }

    public int getNextPage() {
        return nextPage;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public int getTotalCount() {
        return totalCount;
    }
}

 mybatis.xml文件头

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zdyl.business.mapper.SysUserMapper">
    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.zdyl.business.entity.SysUserEntity">
        <id column="user_id" property="userId"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="salt" property="salt"/>
        <result column="email" property="email"/>
        <result column="mobile" property="mobile"/>
        <result column="status" property="status"/>
        <result column="create_user_id" property="createUserId"/>
        <result column="create_time" property="createTime"/>
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        user_id, username, password, salt, email, mobile, status,create_user_id,create_time
    </sql>
    <select id="getOneUser" resultMap="BaseResultMap">
        select <include refid="Base_Column_List"></include> from sys_user where user_id=#{id}
    </select>
</mapper>

 

 

 

 

 

posted @ 2020-06-03 15:35  william_zhao  阅读(958)  评论(0编辑  收藏  举报