溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Mybatis-Plus的搭建方法

發(fā)布時間:2021-02-22 10:46:43 來源:億速云 閱讀:313 作者:小新 欄目:編程語言

這篇文章主要介紹了Mybatis-Plus的搭建方法,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

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

中文文檔 :http://baomidou.oschina.io/mybatis-plus-doc/#/

本文介紹包括

1)如何搭建
2)代碼生成(controller、service、mapper、xml)
3)單表的CRUD、條件查詢、分頁 基類已經(jīng)為你做好了

一、如何搭建

1. 首先我們創(chuàng)建一個 springboot 工程 --> https://start.spring.io/

Mybatis-Plus的搭建方法

2. maven 依賴

  <dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-boot-starter</artifactId>
   <version>2.3</version>
  </dependency>
  <!-- velocity 依賴,用于代碼生成 -->
  <dependency>
   <groupId>org.apache.velocity</groupId>
   <artifactId>velocity-engine-core</artifactId>
   <version>2.0</version>
  </dependency>

3. 配置(因?yàn)楦杏X太啰嗦,這里省略了數(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
#這里需要改成你的類
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

配置類 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();
 }

 /*
  * 分頁插件,自動識別數(shù)據(jù)庫類型 多租戶,請參考官網(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;

/**
 * 注入公共字段自動填充,任選注入方式即可
 */
//@Component
public class MyMetaObjectHandler extends MetaObjectHandler {

 protected final static Logger logger = LoggerFactory.getLogger(Application.class);

 @Override
 public void insertFill(MetaObject metaObject) {
  logger.info("新增的時候干點(diǎn)不可描述的事情");
 }

 @Override
 public void updateFill(MetaObject metaObject) {
  logger.info("更新的時候干點(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>
 * 測試生成代碼
 * </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);//修改替換成你需要的表名,多個表名傳數(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)基本完成了,下面就可以開始使用了!

三、使用 Mybatis-Plus

首先我們執(zhí)行 上面的 generateCode() 會為我們基于 表結(jié)構(gòu) 生成以下代碼(xml是我手動移到下面的),service 和 mapper 已經(jīng)繼承了基類,為我們封裝了很多方法,下面看幾個簡單的例子。

Mybatis-Plus的搭建方法

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 殷天文
 * @since 2018-05-31
 */
@Controller
@RequestMapping("/cable")
public class CableController {
 
 @Autowired private CableService cableService;
 
 /**
  * list 查詢測試
  * 
  */
 @RequestMapping("/1")
 @ResponseBody
 public Object test1() {
  // 構(gòu)造實(shí)體對應(yīng)的 EntityWrapper 對象,進(jì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";
 }
 
 /**
  * 分頁 查詢測試
  */
 @RequestMapping("/2")
 @ResponseBody
 public Object test2() {
  // 構(gòu)造實(shí)體對應(yīng)的 EntityWrapper 對象,進(jì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;
 }
 
 /**
  * 自定義查詢字段
  */
 @RequestMapping("/3")
 @ResponseBody
 public Object test3() {
  Object vl = null;
  // 構(gòu)造實(shí)體對應(yīng)的 EntityWrapper 對象,進(jì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 為空時,不拼接
  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("測試光纜");
  cableService.insert(c);
  return "ok";
 }
 
 /**
  * update
  */
 @RequestMapping("/5")
 @ResponseBody
 public Object test5() {
  Cable c = cableService.selectById(22284l);
  c.setName("測試光纜2222");
  c.setType(1);
  cableService.updateById(c);
  return "ok";
 } 
}

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Mybatis-Plus的搭建方法”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI