电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

SpringBoot整合MybatisPlus的教程詳解

瀏覽:163日期:2023-04-06 17:54:46

Mybatis-Plus(簡(jiǎn)稱(chēng)MP)是一個(gè) Mybatis 的增強(qiáng)工具,在 Mybatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開(kāi)發(fā)、提高效率而生。

它已經(jīng)封裝好了一些crud方法,對(duì)于非常常見(jiàn)的一些sql我們不用寫(xiě)xml了,直接調(diào)用這些方法就行,但它也是支持我們自己手動(dòng)寫(xiě)xml。

幫我們擺脫了用mybatis需要寫(xiě)大量的xml文件的麻煩,非常安逸哦

用過(guò)就不想用其他了,太舒服了

好了,我們開(kāi)始整合整合

SpringBoot整合MybatisPlus的教程詳解

新建一個(gè)SpringBoot的工程

SpringBoot整合MybatisPlus的教程詳解

這里是我整合完一個(gè)最終的結(jié)構(gòu),可以參考一下

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd'> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.zkb</groupId> <artifactId>spring-boot-mybatisplus</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-mybatisplus</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <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>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.30</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

引入相關(guān)的jar包

SpringBoot整合MybatisPlus的教程詳解

可以看到我這邊策略也有引入,它與mybatis一樣,也有對(duì)應(yīng)生成代碼的策略,我們直接用這個(gè)來(lái)幫我們把代碼生成就好

package com.example.mybatisplus; import com.baomidou.mybatisplus.core.toolkit.StringPool;import com.baomidou.mybatisplus.generator.AutoGenerator;import com.baomidou.mybatisplus.generator.InjectionConfig;import com.baomidou.mybatisplus.generator.config.*;import com.baomidou.mybatisplus.generator.config.po.TableInfo;import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import java.util.ArrayList;import java.util.List; public class MysqlGenerator { 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('zkb'); gc.setOpen(false); // service 命名方式 gc.setServiceName('%sService'); // service impl 命名方式 gc.setServiceImplName('%sServiceImpl'); gc.setMapperName('%sMapper'); gc.setXmlName('%sMapper'); gc.setFileOverride(true); gc.setActiveRecord(true); // XML 二級(jí)緩存 gc.setEnableCache(false); // XML ResultMap gc.setBaseResultMap(true); // XML columList gc.setBaseColumnList(false); // gc.setSwagger2(true); 實(shí)體屬性 Swagger2 注解 mpg.setGlobalConfig(gc); // 數(shù)據(jù)源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl('jdbc:mysql://localhost:3306/900?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false'); // dsc.setSchemaName('public'); dsc.setDriverName('com.mysql.cj.jdbc.Driver'); dsc.setUsername('root'); dsc.setPassword('baishou888'); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent('com.zkb'); pc.setEntity('model'); pc.setService('service'); pc.setServiceImpl('service.impl'); mpg.setPackageInfo(pc); // 自定義配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() {// to do nothing } }; // 如果模板引擎是 freemarker String templatePath = '/templates/mapper.xml.ftl'; // 如果模板引擎是 velocity // String templatePath = '/templates/mapper.xml.vm'; // 自定義輸出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定義配置會(huì)被優(yōu)先輸出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) {// 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化!!return projectPath + '/src/main/resources/mappers/' + '/' + tableInfo.getEntityName() + 'Mapper' + StringPool.DOT_XML; } }); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {// 判斷自定義文件夾是否需要?jiǎng)?chuàng)建checkDir('調(diào)用默認(rèn)方法創(chuàng)建的目錄');return false; } }); */ cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定義輸出模板 //指定自定義模板路徑,注意不要帶上.ftl/.vm, 會(huì)根據(jù)使用的模板引擎自動(dòng)識(shí)別 // templateConfig.setEntity('templates/entity2.java'); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 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(true); strategy.setRestControllerStyle(true); // 公共父類(lèi)// strategy.setSuperControllerClass('com.baomidou.ant.common.BaseController'); // 寫(xiě)于父類(lèi)中的公共字段// strategy.setSuperEntityColumns('id'); strategy.setInclude(new String[]{'t_user'}); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix('t' + '_'); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); }}

我有一個(gè)t_user的表

CREATE TABLE `t_user` ( `id` bigint NOT NULL AUTO_INCREMENT, `username` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `nickname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `gender` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `telephone` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `registerdate` datetime NOT NULL, `address` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `addTime` timestamp NOT NULL DEFAULT ’2015-09-15 00:00:00’, `updateTime` timestamp NOT NULL DEFAULT ’2015-09-15 00:00:00’ ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=44138653810545248 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

我是直接針對(duì)它執(zhí)行策略的,

SpringBoot整合MybatisPlus的教程詳解

這幾個(gè)文件都是策略生成的,我沒(méi)有去動(dòng)過(guò)

package com.zkb.conf; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration; /** * 配置分頁(yè)插件 * */@Configurationpublic class MybatisPlusConfig { /** * 分頁(yè)插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }}

server: port: 8081 servlet: context-path: / spring: datasource: # mysql5.x 配置,高版本需要加useSSL=false #url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false # mysql8.0 需要加&useSSL=false&serverTimezone=UTC url: jdbc:mysql://localhost:3306/900?zeroDateTimeBehavior=convertToNull&characterEncoding=utf8&useSSL=false&serverTimezone=UTC username: root password: baishou888 # mysql8.0 驅(qū)動(dòng) driver-class-name: com.mysql.cj.jdbc.Driver # mysql5.x 驅(qū)動(dòng) #driver-class-name: com.mysql.jdbc.Driver debug: false #Druid# name: test type: com.alibaba.druid.pool.DruidDataSource 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 jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 mybatis-plus: configuration: map-underscore-to-camel-case: true auto-mapping-behavior: full log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath*:mapper/**/*Mapper.xml global-config: # 邏輯刪除配置 db-config: # 刪除前 logic-not-delete-value: 1 # 刪除后 logic-delete-value: 0

package com.zkb; import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication@MapperScan('com.zkb.mapper')public class SpringBootMybatisplusApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMybatisplusApplication.class, args); } }

@MapperScan('com.zkb.mapper')一定是掃描到自己mapper的接口類(lèi)

package com.zkb.controller; import com.zkb.model.User;import com.zkb.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <p> * 前端控制器 * </p> * * @author zkb * @since 2020-11-23 */@RestController@RequestMapping('/user')public class UserController { @Autowired private UserService userService; @GetMapping('/getUser') public User getUser(){ return userService.getById(1231); } }

寫(xiě)了一個(gè)get方法來(lái)測(cè)試自己是否與mybatis-plus整合成功,所以直接調(diào)用了mybatis-plus內(nèi)置的方法

當(dāng)然數(shù)據(jù)庫(kù)我自己手動(dòng)寫(xiě)了一個(gè)id為1231的數(shù)據(jù)

SpringBoot整合MybatisPlus的教程詳解

可以看到整合成功了,對(duì)吧,真的是超級(jí)簡(jiǎn)單

點(diǎn)擊此處demo下載,需要自取

到此這篇關(guān)于SpringBoot整合MybatisPlus的文章就介紹到這了,更多相關(guān)SpringBoot整合MybatisPlus內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 球磨机 选矿球磨机 棒磨机 浮选机 分级机 选矿设备厂家 | 成都软件开发_OA|ERP|CRM|管理系统定制开发_成都码邻蜀科技 | 澳门精准正版免费大全,2025新澳门全年免费,新澳天天开奖免费资料大全最新,新澳2025今晚开奖资料,新澳马今天最快最新图库-首页-东莞市傲马网络科技有限公司 | 防锈油-助焊剂-光学玻璃清洗剂-贝塔防锈油生产厂家 | 无轨电动平车_轨道平车_蓄电池电动平车★尽在新乡百特智能转运设备有限公司 | 福建自考_福建自学考试网 | 压滤机滤板_厢式_隔膜_板框压滤机滤板厂家价格型号材质-大凯环保 | TPE_TPE热塑性弹性体_TPE原料价格_TPE材料厂家-惠州市中塑王塑胶制品公司- 中塑王塑胶制品有限公司 | 臭氧实验装置_实验室臭氧发生器-北京同林臭氧装置网 | 百度爱采购运营研究社社群-店铺托管-爱采购代运营-良言多米网络公司 | 亳州网络公司 - 亳州网站制作 - 亳州网站建设 - 亳州易天科技 | 石英陶瓷,石英坩埚,二氧化硅陶瓷-淄博百特高新材料有限公司 | 低噪声电流前置放大器-SR570电流前置放大器-深圳市嘉士达精密仪器有限公司 | 柴油机_柴油发电机_厂家_品牌-江苏卡得城仕发动机有限公司 | 长江船运_国内海运_内贸船运_大件海运|运输_船舶运输价格_钢材船运_内河运输_风电甲板船_游艇运输_航运货代电话_上海交航船运 | 塑胶跑道_学校塑胶跑道_塑胶球场_运动场材料厂家_中国塑胶跑道十大生产厂家_混合型塑胶跑道_透气型塑胶跑道-广东绿晨体育设施有限公司 | Copeland/谷轮压缩机,谷轮半封闭压缩机,谷轮涡旋压缩机,型号规格,技术参数,尺寸图片,价格经销商 CTP磁天平|小电容测量仪|阴阳极极化_双液系沸点测定仪|dsj电渗实验装置-南京桑力电子设备厂 | 塑料熔指仪-塑料熔融指数仪-熔体流动速率试验机-广东宏拓仪器科技有限公司 | 福尔卡(北京)新型材料技术股份有限公司 | 高压无油空压机_无油水润滑空压机_水润滑无油螺杆空压机_无油空压机厂家-科普柯超滤(广东)节能科技有限公司 | 货车视频监控,油管家,货车油管家-淄博世纪锐行电子科技 | 扒渣机,铁水扒渣机,钢水扒渣机,铁水捞渣机,钢水捞渣机-烟台盛利达工程技术有限公司 | 集装箱展厅-住人集装箱住宿|建筑|房屋|集装箱售楼处-山东锐嘉科技工程有限公司 | 艾乐贝拉细胞研究中心 | 国家组织工程种子细胞库华南分库 | 捆扎机_气动捆扎机_钢带捆扎机-沈阳海鹞气动钢带捆扎机公司 | 玖容气动液压设备有限公司-气液增压缸_压力机_增压机_铆接机_增压器 | 磁力抛光机_磁力研磨机_磁力去毛刺机_精密五金零件抛光设备厂家-冠古科技 | 次氯酸钠厂家,涉水级次氯酸钠,三氯化铁生产厂家-淄博吉灿化工 | 北京律师事务所_房屋拆迁律师_24小时免费法律咨询_云合专业律师网 | 环氧乙烷灭菌器_压力蒸汽灭菌器_低温等离子过氧化氢灭菌器 _低温蒸汽甲醛灭菌器_清洗工作站_医用干燥柜_灭菌耗材-环氧乙烷灭菌器_脉动真空压力蒸汽灭菌器_低温等离子灭菌设备_河南省三强医疗器械有限责任公司 | 餐饮加盟网_特色餐饮加盟店_餐饮连锁店加盟 | 通风气楼_通风天窗_屋顶风机-山东美创通风设备有限公司 | 光栅尺_Magnescale探规_磁栅尺_笔式位移传感器_苏州德美达 | 聚合氯化铝厂家-聚合氯化铝铁价格-河南洁康环保科技 | 武汉EPS线条_EPS装饰线条_EPS构件_湖北博欧EPS线条厂家 | 石家庄小程序开发_小程序开发公司_APP开发_网站制作-石家庄乘航网络科技有限公司 | 欧洲MV日韩MV国产_人妻无码一区二区三区免费_少妇被 到高潮喷出白浆av_精品少妇自慰到喷水AV网站 | 法钢特种钢材(上海)有限公司 - 耐磨钢板、高强度钢板销售加工 阀门智能定位器_电液动执行器_气动执行机构-赫尔法流体技术(北京)有限公司 | 污水/卧式/潜水/钻井/矿用/大型/小型/泥浆泵,价格,参数,型号,厂家 - 安平县鼎千泵业制造厂 | 石家庄救护车出租_重症转院_跨省跨境医疗转送_活动赛事医疗保障_康复出院_放弃治疗_腾康26年医疗护送转诊团队 | 杭州荣奥家具有限公司-浙江办公家具,杭州办公家具厂 |