MyBatis-Plus集成Druid環(huán)境搭建的詳細(xì)教程
一、簡(jiǎn)介
Mybatis-Plus是一款 MyBatis 動(dòng)態(tài) sql 自動(dòng)注入 crud 簡(jiǎn)化 增 刪 改 查 操作中間件。啟動(dòng)加載 XML 配置時(shí)注入 mybatis 單表 動(dòng)態(tài) SQL 操作 ,為簡(jiǎn)化開發(fā)工作、提高生產(chǎn)率而生。Mybatis-Plus 啟動(dòng)注入非攔截實(shí)現(xiàn)、性能更優(yōu)。
1.1、原理
1.2、特性
- 無(wú)侵入:Mybatis-Plus 在 Mybatis 的基礎(chǔ)上進(jìn)行擴(kuò)展,只做增強(qiáng)不做改變,引入 Mybatis-Plus 不會(huì)對(duì)您現(xiàn)有的 Mybatis 構(gòu)架產(chǎn)生任何影響,而且 MP 支持所有 Mybatis 原生的特性
- 依賴少:僅僅依賴 Mybatis 以及 Mybatis-Spring
- 損耗?。?jiǎn)?dòng)即會(huì)自動(dòng)注入基本CURD,性能基本無(wú)損耗,直接面向?qū)ο蟛僮?/li>
- 預(yù)防Sql注入:內(nèi)置Sql注入剝離器,有效預(yù)防Sql注入攻擊
- 通用CRUD操作:內(nèi)置通用 Mapper、通用 Service,僅僅通過少量配置即可實(shí)現(xiàn)單表大部分 CRUD 操作,更有強(qiáng)大的條件構(gòu)造器,滿足各類使用需求
- 多種主鍵策略:支持多達(dá)4種主鍵策略(內(nèi)含分布式唯一ID生成器),可自由配置,完美解決主鍵問題
- 支持熱加載:Mapper 對(duì)應(yīng)的 XML 支持熱加載,對(duì)于簡(jiǎn)單的 CRUD 操作,甚至可以無(wú) XML 啟動(dòng)
- 支持ActiveRecord:支持 ActiveRecord 形式調(diào)用,實(shí)體類只需繼承 Model 類即可實(shí)現(xiàn)基本 CRUD 操作
- 支持代碼生成:采用代碼或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 層代碼,支持模板引擎,更有超多自定義配置等您來使用(P.S. 比 Mybatis 官方的 Generator 更加強(qiáng)大!)
- 支持自定義全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 支持關(guān)鍵詞自動(dòng)轉(zhuǎn)義:支持?jǐn)?shù)據(jù)庫(kù)關(guān)鍵詞(order、key......)自動(dòng)轉(zhuǎn)義,還可自定義關(guān)鍵詞
- 內(nèi)置分頁(yè)插件:基于Mybatis物理分頁(yè),開發(fā)者無(wú)需關(guān)心具體操作,配置好插件之后,寫分頁(yè)等同于普通List查詢
- 內(nèi)置性能分析插件:可輸出Sql語(yǔ)句以及其執(zhí)行時(shí)間,建議開發(fā)測(cè)試時(shí)啟用該功能,能有效解決慢查詢
- 內(nèi)置全局?jǐn)r截插件:提供全表 delete 、 update 操作智能分析阻斷,預(yù)防誤操作
1.3、簡(jiǎn)化
MP簡(jiǎn)化了MyBatis的單表基本操作,提供了兩種操作方式:
(1)、傳統(tǒng)模式
Mybatis-Plus 通過 EntityWrapper(簡(jiǎn)稱 EW,MP 封裝的一個(gè)查詢條件構(gòu)造器)或者 Condition(與EW類似) 來讓用戶自由的構(gòu)建查詢條件,簡(jiǎn)單便捷,沒有額外的負(fù)擔(dān),能夠有效提高開發(fā)效率。
(2)、ActiveRecord模式
Active Record(簡(jiǎn)稱AR)模式是軟件里的一種架構(gòu)性模式,主要概念是關(guān)系型數(shù)據(jù)庫(kù)中的數(shù)據(jù)在內(nèi)存中以對(duì)象的形式存儲(chǔ)。由Martin Fowler在其2003年初版的書籍《Patterns of Enterprise Application Architecture》命名。遵循該模式的對(duì)象接口一般包括如Insert, Update, 和 Delete這樣的函數(shù),以及對(duì)應(yīng)于底層數(shù)據(jù)庫(kù)表字段的相關(guān)屬性。
AR模式是一種訪問數(shù)據(jù)庫(kù)數(shù)據(jù)的方式。數(shù)據(jù)表或視圖被映射成一個(gè)類。每個(gè)對(duì)象實(shí)例則對(duì)應(yīng)于表的一條記錄。對(duì)象被創(chuàng)建后,通過save就可以向表中新添一行記錄。當(dāng)對(duì)象被更新時(shí),表中相應(yīng)記錄也被更新。這個(gè)包裹類通過屬性或方法的形式實(shí)現(xiàn)訪問表或視圖中的每一個(gè)字段。
該模式主要被對(duì)象持久化工具采用,用于對(duì)象關(guān)系映射 (ORM). 典型的,外鍵關(guān)系會(huì)以合適的對(duì)象實(shí)例屬性的形式暴露訪問。
1.4、常用實(shí)體注解
1.表名注解@TableName
2.主鍵注解@TableId
3.字段注解@TableFieId
4.序列主鍵策略注解@KeySequence
二、搭建
環(huán)境:
IDEA
Spring Boot-2.0
MyBatis-Plus-2.2.0
MyBatisPlus-spring-boot-starter-1.0.5
druid-spring-boot-starter-1.1.9
首先創(chuàng)建SpringBoot Maven項(xiàng)目,然后加入以下依賴:
<?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"> <modelVersion>4.0.0</modelVersion> <groupId>com.fendo.mybatis.plus</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>mybatis-plus</name> <description>mybatis-plus 示例</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <mybatisplus-spring-boot-starter.version>1.0.5</mybatisplus-spring-boot-starter.version> <mybatisplus.version>2.2.0</mybatisplus.version> <fastjson.version>1.2.39</fastjson.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- mybatis-plus begin --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatisplus-spring-boot-starter</artifactId> <version>${mybatisplus-spring-boot-starter.version}</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>${mybatisplus.version}</version> </dependency> <!-- mybatis-plus end --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>com.jayway.restassured</groupId> <artifactId>rest-assured</artifactId> <version>2.9.0</version> </dependency> <!--Swagger UI--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
然后新建application.yml配置文件
# Tomcat server: tomcat: uri-encoding: UTF-8 max-threads: 1000 min-spare-threads: 30 port: 8080 connection-timeout: 5000 #datasource spring: datasource: name: fendo url: jdbc:mysql://localhost:3306/fendo_plus_boot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false username: root password: root type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 spring.datasource.filters: stat,wall,log4j connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # jackson時(shí)間格式化 jackson: time-zone: GMT+8 date-format: yyyy-MM-dd HH:mm:ss thymeleaf: cache: false prefix: classpath:/templates/ suffix: .html mode: LEGACYHTML5 encoding: UTF-8 check-template: false enabled: false resources: # 指定靜態(tài)資源的路徑 static-locations: classpath:/static/,classpath:/views/ mvc: view: prefix: /WEB-INF/ suffix: .jsp # Mybatis-Plus 配置 mybatis-plus: mapper-locations: classpath:/mapper/*Mapper.xml typeAliasesPackage: com.fendo.mybatis.plus.entity typeEnumsPackage: com.fendo.mybatis.plus.entity.enums # global-config: # id-type: 2 # field-strategy: 2 # db-column-underline: true # refresh-mapper: true # #capital-mode: true # #key-generator: com.baomidou.springboot.xxx # logic-delete-value: 0 # logic-not-delete-value: 1 # sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector # #meta-object-handler: com.baomidou.springboot.xxx # #sql-injector: com.baomidou.springboot.xxx # configuration: # map-underscore-to-camel-case: true # cache-enabled: false global-config: id-type: 3 #0:數(shù)據(jù)庫(kù)ID自增 1:用戶輸入id 2:全局唯一id(IdWorker) 3:全局唯一ID(uuid) db-column-underline: false refresh-mapper: true configuration: map-underscore-to-camel-case: true cache-enabled: true #配置的緩存的全局開關(guān) lazyLoadingEnabled: true #延時(shí)加載的開關(guān) multipleResultSetsEnabled: true #開啟的話,延時(shí)加載一個(gè)屬性時(shí)會(huì)加載該對(duì)象全部屬性,否則按需加載屬性 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql語(yǔ)句,調(diào)試用
創(chuàng)建MyBatis-Plus配置類MybatisPlusConfig
/** * projectName: fendo-plus-boot * fileName: MybatisPlusConfig.java * packageName: com.fendo.mybatis.plus.config * date: 2018-01-12 23:13 * copyright(c) 2017-2020 xxx公司 */ package com.fendo.mybatis.plus.config; import com.baomidou.mybatisplus.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.plugins.PerformanceInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @version: V1.0 * @author: fendo * @className: MybatisPlusConfig * @packageName: com.fendo.mybatis.plus.config * @description: Mybatis-plus配置類 * @data: 2018-01-12 23:13 **/ @Configuration @MapperScan("com.fendo.mybatis.plus.mapper*") public class MybatisPlusConfig { /** * mybatis-plus SQL執(zhí)行效率插件【生產(chǎn)環(huán)境可以關(guān)閉】 */ @Bean public PerformanceInterceptor performanceInterceptor() { return new PerformanceInterceptor(); } /** * 分頁(yè)插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }
三、測(cè)試
首先創(chuàng)建User表
CREATE TABLE `user` ( `id` varchar(32) NOT NULL, `name` varchar(255) DEFAULT NULL, `age` int(2) DEFAULT NULL, `sex` int(2) DEFAULT NULL, `create_by` varchar(255) DEFAULT NULL, `create_date` datetime DEFAULT NULL, `update_by` varchar(255) DEFAULT NULL, `update_date` datetime DEFAULT NULL, `remarks` varchar(255) DEFAULT NULL, `del_flag` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
然后創(chuàng)建controller,entity,service,mapper,項(xiàng)目結(jié)構(gòu)如下所示:
Controller測(cè)試類如下:
/** * projectName: mybatis-plus * fileName: UserController.java * packageName: com.fendo.mybatis.plus.controller * date: 2018-03-24 19:07 * copyright(c) 2017-2020 xxx公司 */ package com.fendo.mybatis.plus.controller; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.plugins.pagination.PageHelper; import com.fendo.mybatis.plus.common.utils.IdGen; import com.fendo.mybatis.plus.entity.UserEntity; import com.fendo.mybatis.plus.entity.enums.AgeEnum; import com.fendo.mybatis.plus.entity.enums.SexEnum; import com.fendo.mybatis.plus.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @version: V1.0 * @author: fendo * @className: UserController * @packageName: com.fendo.mybatis.plus.controller * @description: 用戶Controller * @data: 2018-03-24 19:07 **/ @RestController @RequestMapping("/user") @Api("用戶操作接口") public class UserController { @Autowired private UserService userService; /** * 分頁(yè) PAGE */ @GetMapping("/page") @ApiOperation(value = "用戶分頁(yè)數(shù)據(jù)", response = UserEntity.class) @ApiResponse(code = 200, message = "success") public Page<UserEntity> test() { return userService.selectPage(new Page<UserEntity>(0,12)); } /** * AR 部分測(cè)試 */ @GetMapping("/insert") public Page<UserEntity> insert() { UserEntity user = new UserEntity(IdGen.getUUID(), "testAr", AgeEnum.ONE, SexEnum.FEMALE); System.err.println("刪除所有:" + user.delete(null)); user.insert(); System.err.println("查詢插入結(jié)果:" + user.selectById().toString()); user.setName("mybatis-plus-ar"); System.err.println("更新:" + user.updateById()); return user.selectPage(new Page<UserEntity>(0, 12), null); } /** * 增刪改查 CRUD */ @GetMapping("/crud") public UserEntity crud() { System.err.println("刪除一條數(shù)據(jù):" + userService.deleteById("85349feb19f04fa78a7a717f4dce031f")); System.err.println("deleteAll:" + userService.deleteAll()); String IdGens = IdGen.getUUID(); System.err.println("插入一條數(shù)據(jù):" + userService.insert(new UserEntity(IdGens, "張三", AgeEnum.TWO, SexEnum.FEMALE))); UserEntity user = new UserEntity("張三", AgeEnum.TWO, SexEnum.MALE); boolean result = userService.insert(user); // 自動(dòng)回寫的ID String id = user.getId(); System.err.println("插入一條數(shù)據(jù):" + result + ", 插入信息:" + user.toString()); System.err.println("查詢:" + userService.selectById(id).toString()); System.err.println("更新一條數(shù)據(jù):" + userService.updateById(new UserEntity(IdGens, "三毛", AgeEnum.ONE, SexEnum.FEMALE))); for (int i = 0; i < 5; ++i) { userService.insert(new UserEntity( IdGen.getUUID(), "張三" + i, AgeEnum.ONE, SexEnum.FEMALE)); } Page<UserEntity> userListPage = userService.selectPage(new Page<UserEntity>(1, 5), new EntityWrapper<>(new UserEntity())); System.err.println("total=" + userListPage.getTotal() + ", current list size=" + userListPage.getRecords().size()); return userService.selectById(IdGens); } /** * 插入 OR 修改 */ @GetMapping("/save") public UserEntity save() { String IdGens = IdGen.getUUID(); UserEntity user = new UserEntity(IdGens, "王五", AgeEnum.ONE, SexEnum.FEMALE); userService.insertOrUpdate(user); return userService.selectById(IdGens); } @GetMapping("/add") public Object addUser() { UserEntity user = new UserEntity(IdGen.getUUID(), "張三'特殊`符號(hào)", AgeEnum.TWO, SexEnum.FEMALE); JSONObject result = new JSONObject(); result.put("result", userService.insert(user)); return result; } @GetMapping("/selectsql") public Object getUserBySql() { JSONObject result = new JSONObject(); result.put("records", userService.selectListBySQL()); return result; } /** * 7、分頁(yè) size 一頁(yè)顯示數(shù)量 current 當(dāng)前頁(yè)碼 * 方式一:http://localhost:8080/user/page?size=1¤t=1 * 方式二:http://localhost:8080/user/pagehelper?size=1¤t=1 */ // 參數(shù)模式分頁(yè) @GetMapping("/pages") public Object page(Page page) { return userService.selectPage(page); } // ThreadLocal 模式分頁(yè) @GetMapping("/pagehelper") public Object pagehelper(Page page) { PageHelper.setPagination(page); page.setRecords(userService.selectList(null)); page.setTotal(PageHelper.freeTotal());//獲取總數(shù)并釋放資源 也可以 PageHelper.getTotal() return page; } /** * 測(cè)試事物 * http://localhost:8080/user/test_transactional<br> * 訪問如下并未發(fā)現(xiàn)插入數(shù)據(jù)說明事物可靠!!<br> * http://localhost:8080/user/test<br> * <br> * 啟動(dòng) Application 加上 @EnableTransactionManagement 注解其實(shí)可無(wú)默認(rèn)貌似就開啟了<br> * 需要事物的方法加上 @Transactional 必須的哦!! */ @Transactional @GetMapping("/test_transactional") public void testTransactional() { String IdGens = IdGen.getUUID(); userService.insert(new UserEntity(IdGens, "測(cè)試事物", AgeEnum.ONE, SexEnum.FEMALE)); System.out.println(" 這里手動(dòng)拋出異常,自動(dòng)回滾數(shù)據(jù) : " + IdGens); throw new RuntimeException(); } }
四、代碼生成
創(chuàng)建測(cè)試類GeneratorStart
/** * projectName: fendo-plus-boot * fileName: GeneratorStart.java * packageName: com.fendo.shiro.generator * date: 2018-01-15 19:59 * copyright(c) 2017-2020 xxx公司 */ package com.gzsys.modules.gen; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.DbType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @version: V1.0 * @author: fendo * @className: GeneratorStart * @packageName: com.gzsys.modules.gen * @description: 代碼生成器 * @data: 2018-01-15 19:59 **/ public class GeneratorStart { public static void main(String[] args) { String packageName = "com.gzsys.modules.yun"; boolean serviceNameStartWithI = false;//user -> UserService, 設(shè)置成true: user -> IUserService generateByTables(serviceNameStartWithI, packageName, "USER_LOGIN"); } private static void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) { // 全局配置 GlobalConfig config = new GlobalConfig(); AutoGenerator mpg = new AutoGenerator(); String dbUrl = "jdbc:oracle:thin:@//106.14.160.67:1521/test"; DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDbType(DbType.ORACLE) .setUrl(dbUrl) .setUsername("test") .setPassword("Eru43wPo") .setDriverName("oracle.jdbc.driver.OracleDriver"); // 策略配置 StrategyConfig strategyConfig = new StrategyConfig(); strategyConfig .setCapitalMode(true) // 全局大寫命名 ORACLE 注意 .setEntityLombokModel(false) //實(shí)體 是否為lombok模型(默認(rèn) false) .setDbColumnUnderline(true) //表名、字段名、是否使用下劃線命名 .setNaming(NamingStrategy.underline_to_camel) //表名生成策略 .setInclude(tableNames);//修改替換成你需要的表名,多個(gè)表名傳數(shù)組 // strategyConfig.setExclude(new String[]{"test"}); // 排除生成的表 // 自定義實(shí)體父類 strategyConfig.setSuperEntityClass("com.gzsys.common.persistence.BaseEntity"); // 自定義實(shí)體,公共字段 strategyConfig.setSuperEntityColumns(new String[] { "ID", "CREATE_TIME", "CREATE_NAME" , "UPDATE_TIME", "UPDATE_NAME", "STATE"}); // 自定義 mapper 父類 // strategyConfig.setSuperMapperClass("com.baomidou.demo.TestMapper"); // 自定義 service 父類 //strategyConfig.setSuperServiceClass("com.baomidou.demo.TestService"); // 自定義 service 實(shí)現(xiàn)類父類 //strategyConfig.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl"); // 自定義 controller 父類 strategyConfig.setSuperControllerClass("com.gzsys.common.base.controller.BaseController"); // 【實(shí)體】是否生成字段常量(默認(rèn) false) // public static final String ID = "test_id"; // strategyConfig.setEntityColumnConstant(true); // 【實(shí)體】是否為構(gòu)建者模型(默認(rèn) false) // public User setName(String name) {this.name = name; return this;} // strategyConfig.setEntityBuliderModel(true); config.setActiveRecord(true) //是否 開啟 ActiveRecord 模式 .setAuthor("fendo") .setOutputDir("d:\\codeGen") .setFileOverride(true) .setActiveRecord(true) .setEnableCache(false)// XML 二級(jí)緩存 .setBaseResultMap(true)// XML ResultMap .setBaseColumnList(false);// XML columList if (!serviceNameStartWithI) { config.setServiceName("%sService"); //自定義Service后戳,注意 %s 會(huì)自動(dòng)填充表實(shí)體屬性! } // 注入自定義配置,可以在 VM 中使用 cfg.abc 【可無(wú)】 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); this.setMap(map); } }; // 自定義 xxList.jsp 生成 List<FileOutConfig> focList = new ArrayList<FileOutConfig>(); //focList.add(new FileOutConfig("/template/list.jsp.vm") { // @Override // public String outputFile(TableInfo tableInfo) { // // 自定義輸入文件名稱 // return "D://my_" + tableInfo.getEntityName() + ".jsp"; // } //}); //cfg.setFileOutConfigList(focList); //mpg.setCfg(cfg); // 調(diào)整 xml 生成目錄演示 focList.add(new FileOutConfig("/templates/mapper.xml.vm") { @Override public String outputFile(TableInfo tableInfo) { return "d:\\codeGen/resources/mapping/modules/yun/" + tableInfo.getEntityName() + ".xml"; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 關(guān)閉默認(rèn) xml 生成,調(diào)整生成 至 根目錄 TemplateConfig tc = new TemplateConfig(); tc.setXml(null); mpg.setTemplate(tc); // 自定義模板配置,可以 copy 源碼 mybatis-plus/src/main/resources/templates 下面內(nèi)容修改, // 放置自己項(xiàng)目的 src/main/resources/templates 目錄下, 默認(rèn)名稱一下可以不配置,也可以自定義模板名稱 // TemplateConfig tc = new TemplateConfig(); // tc.setController("..."); // tc.setEntity("..."); // tc.setMapper("..."); // tc.setXml("..."); // tc.setService("..."); // tc.setServiceImpl("..."); // 如上任何一個(gè)模塊如果設(shè)置 空 OR Null 將不生成該模塊。 // mpg.setTemplate(tc); //生成文件 配置 mpg.setGlobalConfig(config) //全局 相關(guān)配置 .setDataSource(dataSourceConfig) //數(shù)據(jù)源配置 .setStrategy(strategyConfig) //數(shù)據(jù)庫(kù)表配置 .setPackageInfo( //包 相關(guān)配置 new PackageConfig() //跟包相關(guān)的配置項(xiàng) .setParent(packageName) //父包名。如果為空,將下面子包名必須寫全部, 否則就只需寫子包名 .setController("controller") //Controller包名 .setEntity("entity") //entity包名 //.setXml("/") ) .execute(); } private void generateByTables(String packageName, String... tableNames) { generateByTables(true, packageName, tableNames); } }
Spring Boot 整合mybatis 與 swagger2
到此這篇關(guān)于MyBatis-Plus集成Druid環(huán)境搭建的詳細(xì)教程的文章就介紹到這了,更多相關(guān)MyBatis-Plus環(huán)境搭建內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳細(xì)介紹Java關(guān)鍵字throw?throws?Throwable的用法與區(qū)別
這篇文章主要介紹了java中throws與throw及Throwable的用法和區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04Java設(shè)計(jì)模式中的設(shè)計(jì)原則之合成復(fù)用原則詳解
這篇文章主要介紹了Java設(shè)計(jì)模式中的設(shè)計(jì)原則之合成復(fù)用原則詳解,原則是盡量使用合成/聚合的方式,而不是使用繼承聚合關(guān)系表示的是整體和部分的關(guān)系,整體與部分可以分開,可以理解為成員變量和當(dāng)前類的關(guān)系就是聚合關(guān)系,需要的朋友可以參考下2023-11-11java使用CollectionUtils工具類判斷集合是否為空方式
這篇文章主要介紹了java使用CollectionUtils工具類判斷集合是否為空方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02Spring中數(shù)據(jù)訪問對(duì)象Data Access Object的介紹
今天小編就為大家分享一篇關(guān)于Spring中數(shù)據(jù)訪問對(duì)象Data Access Object的介紹,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01spring單元測(cè)試下模擬rabbitmq的實(shí)現(xiàn)
這篇文章主要介紹了spring單元測(cè)試下模擬rabbitmq的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05如何基于ThreadPoolExecutor創(chuàng)建線程池并操作
這篇文章主要介紹了如何基于ThreadPoolExecutor創(chuàng)建線程池并操作,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11SpringBoot+thymeleaf+Echarts+Mysql 實(shí)現(xiàn)數(shù)據(jù)可視化讀取的示例
本文主要介紹了SpringBoot+thymeleaf+Echarts+Mysql 實(shí)現(xiàn)數(shù)據(jù)可視化讀取的示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04