天天看點

SpringBoot整合MybatisPlus 快速生成代碼 Mybatis系列(三)一、什麼是Mybatis-Plus二、簡單的使用案例三、代碼生成器

一、什麼是Mybatis-Plus

官網位址:https://baomidou.com/

MyBatis-Plus (opens new window)(簡稱 MP)是一個 MyBatis的增強工具,在 MyBatis 的基礎上隻做增強不做改變,為簡化開發、提高效率而生。

特性

  • 無侵入:隻做增強不做改變,引入它不會對現有工程産生影響,如絲般順滑
  • 損耗小:啟動即會自動注入基本 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 操作智能分析阻斷,也可自定義攔截規則,預防誤操作

二、簡單的使用案例

​ 隻需要添加Mybatis-Plus依賴(無需添加mybatis依賴,mybatis-plus的依賴已經包含),編寫表映射的實體類和Mapper語句(繼承BaseMapper)即可實作對資料庫的通路,BaseMapper已經包含了基本的sql方法,無需編寫Mapper.xml。

資料庫表結構

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `avatar` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `password` varchar(300) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `UK_ob8kqyqqgmefl0aco34akdtpe` (`email`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
           

1. 引入依賴

  • 引入Springboot Starter 父工程
    <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.4.8</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
               
  • 引入依賴

    隻需要引入Spring Boot、MyBatis-Plus、資料庫(Mysql)依賴。

    <!-- springboot -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <!-- mybatis-plus -->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.3.1</version>
            </dependency>
            <!-- mysql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <!-- lombok -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.10</version>
            </dependency>
               
  • 完整依賴檔案
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.8</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-mybatis-plus</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- springboot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
    </dependencies>
</project>
           

2. 實體類

@Data
@Accessors(chain = true)
public class User implements Serializable {
    /**
     * id
     * */
    private Integer id;
    /**
     * 頭像
     * */
    private String avatar;
    /**
     * 郵箱
     * */
    private String email;
    /**
     * 賬号
     * */
    private String name;
    /**
     * 密碼
     * */
    private String password;
    /**
     * 使用者名
     * */
    private String username;
}
           

3. UserMapper

​ 這裡需要繼承BaseMapper接口,BaseMapper提供的

public interface BaseMapper<T> extends Mapper<T> {
    //插入
    int insert(T entity);
    
	//通過主鍵删除
    int deleteById(Serializable id);
	//通過Map字段對應值删除
    int deleteByMap(@Param("cm") Map<String, Object> columnMap);
	//通過條件Wrapper删除
    int delete(@Param("ew") Wrapper<T> wrapper);
	//批量删除
    int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    //更新 通過ID比對
    int updateById(@Param("et") T entity);
	//更新 通過更新條件比對
    int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
	
    //查詢通過主鍵
    T selectById(Serializable id);
	//查詢通過批量
    List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
	//查詢通過Map
    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
	//通過查詢條件構造器查詢,傳回實體
    T selectOne(@Param("ew") Wrapper<T> queryWrapper);
	//通過查詢條件構造器查詢行數
    Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
	//通過查詢條件構造器
    List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

    List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
	//分頁查詢
    <E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);

    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}
           

​ UserMapper.java基礎了BaseMapper,如果啟動類使用了MapperScan注解掃描到Mapper所在的路徑可以不用使用@Mapper。

@Mapper
public interface UserMapper extends BaseMapper<User> {

}
           

​ 啟動類

@MapperScan("com.stopping.mapper")

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

4. 配置檔案

​ 配置資料源資訊

spring:  datasource:    password: root    username: root    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC    driver-class-name: com.mysql.cj.jdbc.Driver
           

5. 測試

@SpringBootTest(classes = MybatisPlusApplication.class)class UserMapperTest {    @Resource    private UserMapper userMapper;    @Test    public void selectUser(){        userMapper.selectList(null).stream().forEach(System.out::println);    }}
           

結果

User(id=1, avatar=null, [email protected], name=stopping, password=$2a$10$HMoRS.lxhl0mQ1D0uKVeFeMl7nQ1ZykhI/8N3z0AiND1HUMNCZk/y, username=admin)User(id=2, avatar=null, [email protected], name=tom, password=123456, username=tom)User(id=3, avatar=null, [email protected], name=job, password=123456, username=job)
           

三、代碼生成器

​ AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個子產品的代碼。

​ 通過資料庫連結反向生成資料庫映射的實體類,以及 Entity、Mapper、Mapper XML、Service、Controller 。這些生成檔案存在在什麼路徑都是可以通過配置實作的。

1. 新增依賴

​ MyBatis-Plus 從

3.0.3

之後移除了代碼生成器與模闆引擎的預設依賴,需要手動添加相關依賴

<dependency>    <groupId>com.baomidou</groupId>    <artifactId>mybatis-plus-generator</artifactId>    <version>3.3.1</version></dependency><dependency>    <groupId>org.freemarker</groupId>    <artifactId>freemarker</artifactId>    <version>2.3.31</version></dependency>
           

2. 使用代碼生成器生成

​ 現在通過代碼生成器生成Test資料庫中的category表相關的代碼

CREATE TABLE `category` (  `id` bigint(20) NOT NULL AUTO_INCREMENT,  `create_time` datetime DEFAULT NULL,  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,  `user_id` bigint(20) DEFAULT NULL,  PRIMARY KEY (`id`) USING BTREE,  KEY `FKpfk8djhv5natgshmxiav6xkpu` (`user_id`) USING BTREE) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
           

​ 生成代碼在下面,下圖是生成後的代碼。

[外鍊圖檔轉存失敗,源站可能有防盜鍊機制,建議将圖檔儲存下來直接上傳(img-S9eIaY4L-1625310411074)(https://i.loli.net/2021/06/28/DlnJFm5VCby6x2t.png)]

3. 測試

@SpringBootTest(classes = MybatisPlusApplication.class)class UserMapperTest {    @Resource    private UserMapper userMapper;    @Resource    private CategoryService categoryService;    @Test    public void selectUser(){        categoryService.lambdaQuery().list().forEach(System.out::println);    }}
           

結果:

Category(id=2, createTime=null, name=預設, userId=1)Category(id=3, createTime=2020-08-20T01:05:05, name=計算機視覺, userId=1)Category(id=4, createTime=2020-08-20T01:05:15, name=Spring, userId=1)Category(id=5, createTime=2020-08-20T01:05:24, name=Mybatis, userId=1)Category(id=6, createTime=2020-08-20T01:05:36, name=資料庫, userId=1)Category(id=7, createTime=2020-08-20T01:05:50, name=設計模式, userId=1)Category(id=8, createTime=2020-08-20T01:13:39, name=代碼編輯器, userId=1)Category(id=9, createTime=2020-08-20T01:21:44, name=伺服器, userId=1)Category(id=10, createTime=2020-08-20T01:23:06, name=Hibernate, userId=1)Category(id=11, createTime=2020-08-20T01:24:38, name=技術相關, userId=1)Category(id=12, createTime=2020-08-20T03:16:06, name=前端, userId=1)Category(id=13, createTime=2020-09-16T03:29:30, name=java, userId=1)
           

示例代碼生成器

/** * @Description GeneratorCode * @Author stopping * @date: 2021/6/28 23:33 */public class GeneratorCode {    /**     * 資料庫連接配接     * */    private static final String dbUrl = "jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8";    /**     * 資料庫賬号     * */    private static final String username = "root";    /**     * 資料庫密碼     * */    private static final String password = "root";    /**     * 子產品名     * */    private static final String moduleName = "/spring-mybatis-plus";    /**     * <p>     * 讀取控制台内容     * @param     * </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.isNotBlank(ipt)) {                return ipt;            }        }        throw new MybatisPlusException("請輸入正确的" + tip + "!");    }    public static void main(String[] args) {        // 代碼生成器        AutoGenerator mpg = new AutoGenerator();        String module = scanner("請輸入子產品名稱");        // 全局配置        GlobalConfig gc = new GlobalConfig();        //D:/code/springboot-orm/spring-mybatis-plus        String projectPath = System.getProperty("user.dir")+moduleName;        System.out.println(projectPath);        //設定檔案路徑和子產品檔案生成        gc.setOutputDir(projectPath+"/src/main/java");        gc.setAuthor("stopping");        //生成類名限制        gc.setMapperName("%sMapper");        gc.setServiceName("%sService");        gc.setServiceImplName("%sServiceImp");        gc.setControllerName("%sController");        gc.setXmlName("%sMapper");        gc.setIdType(IdType.AUTO);        gc.setOpen(false);        //是否覆寫        gc.setFileOverride(true);        //實體屬性 Swagger2 注解        gc.setSwagger2(false);        mpg.setGlobalConfig(gc);        // 資料源配置        DataSourceConfig dsc = new DataSourceConfig();        dsc.setUrl(dbUrl);        dsc.setDriverName("com.mysql.cj.jdbc.Driver");        dsc.setUsername(username);        dsc.setPassword(password);        mpg.setDataSource(dsc);        // 包配置:生成檔案        PackageConfig pc = new PackageConfig();        //包路徑        pc.setParent("com.stopping");        //包路徑下的子包名稱        pc.setMapper("mapper."+module);        pc.setController("controller."+module);        pc.setService("service."+module);        pc.setServiceImpl("service."+module+".imp");        pc.setEntity("model.entity");        pc.setXml("Mapper");        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) {                // 自定義輸出檔案名 , 如果你 Entity 設定了前字尾、此處注意 xml 的名稱會跟着發生變化!!                // Mapper 檔案輸出                String xmlUrl = projectPath + "/src/main/resources/mapper/" + module                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;                System.out.println("xml生成路徑:"+xmlUrl);                return xmlUrl;            }        });          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.setSuperEntityColumns("id");        strategy.setInclude(scanner("表名,多個英文逗号分割").split(","));        strategy.setControllerMappingHyphenStyle(true);        strategy.setTablePrefix(pc.getModuleName() + "_");        //是否生成注解        strategy.setEntityTableFieldAnnotationEnable(true);        mpg.setStrategy(strategy);        mpg.setTemplateEngine(new FreemarkerTemplateEngine());        mpg.execute();    }}
           

繼續閱讀