Mybatis-Plus 搭建與使用入門(mén)(小結(jié))
Mybatis-Plus(簡(jiǎn)稱(chēng)MP)是一個(gè) Mybatis 的增強(qiáng)工具,在 Mybatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開(kāi)發(fā)、提高效率而生。
中文文檔 :http://baomidou.oschina.io/mybatis-plus-doc/#/
本文介紹包括
1)如何搭建
2)代碼生成(controller、service、mapper、xml)
3)單表的CRUD、條件查詢(xún)、分頁(yè) 基類(lèi)已經(jīng)為你做好了
一、如何搭建
1. 首先我們創(chuàng)建一個(gè) springboot 工程 --> https://start.spring.io/

2. maven 依賴(lài)
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>2.3</version> </dependency> <!-- velocity 依賴(lài),用于代碼生成 --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency>
3. 配置(因?yàn)楦杏X(jué)太啰嗦,這里省略了數(shù)據(jù)源的配置)
application.properties
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml mybatis-plus.typeAliasesPackage=com.taven.web.springbootmp.entity mybatis-plus.global-config.id-type=3 mybatis-plus.global-config.field-strategy=2 mybatis-plus.global-config.db-column-underline=true mybatis-plus.global-config.key-generator=com.baomidou.mybatisplus.incrementer.OracleKeyGenerator mybatis-plus.global-config.logic-delete-value=1 mybatis-plus.global-config.logic-not-delete-value=0 mybatis-plus.global-config.sql-injector=com.baomidou.mybatisplus.mapper.LogicSqlInjector #這里需要改成你的類(lèi) mybatis-plus.global-config.meta-object-handler=com.taven.web.springbootmp.MyMetaObjectHandler mybatis-plus.configuration.map-underscore-to-camel-case=true mybatis-plus.configuration.cache-enabled=false mybatis-plus.configuration.jdbc-type-for-null=null
配置類(lèi) MybatisPlusConfig
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.incrementer.H2KeyGenerator;
import com.baomidou.mybatisplus.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.mapper.ISqlInjector;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.taven.web.springbootmp.MyMetaObjectHandler;
@EnableTransactionManagement
@Configuration
@MapperScan("com.taven.web.springbootmp.mapper")
public class MybatisPlusConfig {
/**
* mybatis-plus SQL執(zhí)行效率插件【生產(chǎn)環(huán)境可以關(guān)閉】
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor();
}
/*
* 分頁(yè)插件,自動(dòng)識(shí)別數(shù)據(jù)庫(kù)類(lèi)型 多租戶,請(qǐng)參考官網(wǎng)【插件擴(kuò)展】
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
@Bean
public MetaObjectHandler metaObjectHandler() {
return new MyMetaObjectHandler();
}
/**
* 注入主鍵生成器
*/
@Bean
public IKeyGenerator keyGenerator() {
return new H2KeyGenerator();
}
/**
* 注入sql注入器
*/
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
}
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 注入公共字段自動(dòng)填充,任選注入方式即可
*/
//@Component
public class MyMetaObjectHandler extends MetaObjectHandler {
protected final static Logger logger = LoggerFactory.getLogger(Application.class);
@Override
public void insertFill(MetaObject metaObject) {
logger.info("新增的時(shí)候干點(diǎn)不可描述的事情");
}
@Override
public void updateFill(MetaObject metaObject) {
logger.info("更新的時(shí)候干點(diǎn)不可描述的事情");
}
}
二、代碼生成
執(zhí)行 junit 即可生成controller、service接口及實(shí)現(xiàn)、mapper及xml
import org.junit.Test;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
* <p>
* 測(cè)試生成代碼
* </p>
*
* @author K神
* @date 2017/12/18
*/
public class GeneratorServiceEntity {
@Test
public void generateCode() {
String packageName = "com.taven.web.springbootmp";
boolean serviceNameStartWithI = false;//user -> UserService, 設(shè)置成true: user -> IUserService
generateByTables(serviceNameStartWithI, packageName, "cable", "station");//修改為你的表名
}
private void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {
GlobalConfig config = new GlobalConfig();
String dbUrl = "jdbc:mysql://localhost:3306/communicate";
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL)
.setUrl(dbUrl)
.setUsername("root")
.setPassword("root")
.setDriverName("com.mysql.jdbc.Driver");
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig
.setCapitalMode(true)
.setEntityLombokModel(false)
.setDbColumnUnderline(true)
.setNaming(NamingStrategy.underline_to_camel)
.setInclude(tableNames);//修改替換成你需要的表名,多個(gè)表名傳數(shù)組
config.setActiveRecord(false)
.setEnableCache(false)
.setAuthor("殷天文")
.setOutputDir("E:\\dev\\stsdev\\spring-boot-mp\\src\\main\\java")
.setFileOverride(true);
if (!serviceNameStartWithI) {
config.setServiceName("%sService");
}
new AutoGenerator().setGlobalConfig(config)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(
new PackageConfig()
.setParent(packageName)
.setController("controller")
.setEntity("entity")
).execute();
}
// private void generateByTables(String packageName, String... tableNames) {
// generateByTables(true, packageName, tableNames);
// }
}
到這一步搭建已經(jīng)基本完成了,下面就可以開(kāi)始使用了!
三、使用 Mybatis-Plus
首先我們執(zhí)行 上面的 generateCode() 會(huì)為我們基于 表結(jié)構(gòu) 生成以下代碼(xml是我手動(dòng)移到下面的),service 和 mapper 已經(jīng)繼承了基類(lèi),為我們封裝了很多方法,下面看幾個(gè)簡(jiǎn)單的例子。

/**
* <p>
* 前端控制器
* </p>
*
* @author 殷天文
* @since 2018-05-31
*/
@Controller
@RequestMapping("/cable")
public class CableController {
@Autowired private CableService cableService;
/**
* list 查詢(xún)測(cè)試
*
*/
@RequestMapping("/1")
@ResponseBody
public Object test1() {
// 構(gòu)造實(shí)體對(duì)應(yīng)的 EntityWrapper 對(duì)象,進(jìn)行過(guò)濾查詢(xún)
EntityWrapper<Cable> ew = new EntityWrapper<>();
ew.where("type={0}", 1)
.like("name", "王")
.and("core_number={0}", 24)
.and("is_delete=0");
List<Cable> list = cableService.selectList(ew);
List<Map<String, Object>> maps = cableService.selectMaps(ew);
System.out.println(list);
System.out.println(maps);
return "ok";
}
/**
* 分頁(yè) 查詢(xún)測(cè)試
*/
@RequestMapping("/2")
@ResponseBody
public Object test2() {
// 構(gòu)造實(shí)體對(duì)應(yīng)的 EntityWrapper 對(duì)象,進(jìn)行過(guò)濾查詢(xún)
EntityWrapper<Cable> ew = new EntityWrapper<>();
ew.where("type={0}", 1)
// .like("name", "王")
.and("core_number={0}", 24)
.and("is_delete=0");
Page<Cable> page = new Page<>(1,10);
Page<Cable> pageRst = cableService.selectPage(page, ew);
return pageRst;
}
/**
* 自定義查詢(xún)字段
*/
@RequestMapping("/3")
@ResponseBody
public Object test3() {
Object vl = null;
// 構(gòu)造實(shí)體對(duì)應(yīng)的 EntityWrapper 對(duì)象,進(jìn)行過(guò)濾查詢(xún)
EntityWrapper<Cable> ew = new EntityWrapper<>();
ew.setSqlSelect("id, `name`, "
+ "case type\n" +
"when 1 then '220kv'\n" +
"end typeName")
.where("type={0}", 1)
// .like("name", "王")
.where(false, "voltage_level=#{0}", vl);//當(dāng)vl 為空時(shí),不拼接
Page<Cable> page = new Page<>(1,10);
Page<Cable> pageRst = cableService.selectPage(page, ew);
return pageRst;
}
/**
* insert
*/
@RequestMapping("/4")
@ResponseBody
public Object test4() {
Cable c = new Cable();
c.setName("測(cè)試光纜");
cableService.insert(c);
return "ok";
}
/**
* update
*/
@RequestMapping("/5")
@ResponseBody
public Object test5() {
Cable c = cableService.selectById(22284l);
c.setName("測(cè)試光纜2222");
c.setType(1);
cableService.updateById(c);
return "ok";
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
spring注解如何為bean指定InitMethod和DestroyMethod
這篇文章主要介紹了spring注解如何為bean指定InitMethod和DestroyMethod,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
一些java二進(jìn)制的相關(guān)基礎(chǔ)知識(shí)
這篇文章主要介紹了一些java二進(jìn)制的相關(guān)基礎(chǔ)知識(shí),在Java語(yǔ)言中byte代表最小計(jì)量單位,byte由8位2進(jìn)制數(shù)組成。,需要的朋友可以參考下2019-06-06
Spring Cloud實(shí)現(xiàn)5分鐘級(jí)區(qū)域切換的操作方法
Spring Cloud 2023.x通過(guò)智能路由預(yù)熱、多活數(shù)據(jù)同步和自動(dòng)化流量切換,實(shí)現(xiàn)5分鐘內(nèi)完成跨區(qū)域故障轉(zhuǎn)移,本文以某電商平臺(tái)從AWS亞太切換至阿里云華東的實(shí)戰(zhàn)為例,詳解關(guān)鍵技術(shù)路徑,需要的朋友可以參考下2025-04-04
Sentinel網(wǎng)關(guān)限流與SpringCloud Gateway整合過(guò)程
本文介紹了如何通過(guò)SpringCloudGateway集成阿里的Sentinel進(jìn)行網(wǎng)關(guān)限流,Sentinel作為流量防衛(wèi)兵,提供了豐富的應(yīng)用場(chǎng)景和完備的實(shí)時(shí)監(jiān)控功能,通過(guò)配置路由維度和自定義API維度的限流規(guī)則,實(shí)現(xiàn)了對(duì)微服務(wù)的保護(hù)2024-11-11
詳談Java中的事件監(jiān)聽(tīng)機(jī)制
下面小編就為大家?guī)?lái)一篇詳談Java中的事件監(jiān)聽(tīng)機(jī)制。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06
如何使用Java實(shí)現(xiàn)請(qǐng)求deepseek
這篇文章主要為大家詳細(xì)介紹了如何使用Java實(shí)現(xiàn)請(qǐng)求deepseek功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-02-02

