MybatisPlus的各種功能使用筆記綜合!


官方文檔:https://mybatis.plus/

官方樣例地址:https://gitee.com/baomidou/mybatis-plus-samples

零、MybatisPlus特性:

  • 無侵入,損耗小,強大的CRUD操作。
  • 支持Lambda形式調用,支持多種數據庫。
  • 支持主鍵自動生成,支持ActiveRecord模式。
  • 支持自定義全局通用操作,支持關鍵詞自動轉義。
  • 內置代碼生成器,分頁插件,性能分析插件。
  • 內置全局攔截插件,內置sql注入剝離器。

一、快速開始

前置准備:本文所有代碼樣例包括數據庫腳本均已上傳至碼雲:https://gitee.com/tqbx/springboot-samples-learn

  1. 引入依賴
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>
  1. 配置yml
spring:
  # mysql數據庫連接
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:p6spy:mysql://localhost:3306/eblog?serverTimezone=GMT%2B8
    username: xxx
    password: xxx
    
# mybatis配置
mybatis-plus:
  mapper-locations:
    - classpath*:mapper/*.xml
# logging
logging:
  level:
    root: warn
    com.hyh.mybatisplus.mapper: trace
  pattern:
    console: '%p%m%n'
  1. 編寫MybatisPlus的配置
@Configuration
@MapperScan("com.hyh.mybatisplus.mapper")
public class MybatisPlusConfig {
}
  1. 編寫測試方法
    @Test
    void selectById() {
        User user = mapper.selectById(1087982257332887553L);
        System.out.println(user);
    }

二、常用注解

當遇到不可抗拒因素導致數據庫表與實體表名或字段名不對應時,可以使用注解進行指定。

@Data
@ToString
@TableName("user") //指定表名 也可以使用table-prefix
public class User {

    @TableId //指定主鍵
    private Long id;

    @TableField("name") //指定字段名
    private String name;
    private String email;
    private Integer age;

    private Long managerId;

    @TableField("create_time")
    private Date createTime;

    @TableField(exist = false)//備注[數據庫中無對應的字段]
    private String remark;
}

三、排除非表字段的三種方式

假設實體中存在字段且該字段只是臨時為了存儲某些數據,數據庫表中並沒有,此時有三種方法可以排除這類字段。

  1. 使用transient修飾字段,此時字段無法進行序列化,有時會不符合需求。
  2. 使用static修飾字段,此時字段就歸屬於類了,有時不符合需求。

以上兩種方式在某種意義下,並不能完美解決這個問題,為此,mp提供了下面這種方式:

    @TableField(exist = false)//備注[數據庫中無對應的字段]
    private String remark;

四、MybatisPlus的查詢

博客地址:https://www.cnblogs.com/summerday152/p/13869233.html

代碼樣例地址:spring-boot-mybatis-plus學習

五、分頁插件使用

文檔地址:分頁插件使用

我們這里采用SpringBoot的注解方式使用插件:

@Configuration
@MapperScan("com.hyh.mybatisplus.mapper")
public class MybatisPlusConfig {

    /**
     * 新的分頁插件,一緩和二緩遵循mybatis的規則,需要設置 MybatisConfiguration#useDeprecatedExecutor = false 避免緩存出現問題(該屬性會在舊插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}

測試分頁:

    @Test
    public void selectPage(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("age",26);
        //Page<User> page = new Page<>(1,2);
        Page<User> page = new Page<>(1,2,false);
        Page<User> p = mapper.selectPage(page, queryWrapper);
        System.out.println("總頁數: " + p.getPages());
        System.out.println("總記錄數: " + p.getTotal());
        List<User> records = p.getRecords();
        records.forEach(System.out::println);
    }

七、MyBatisPlus代碼生成器整合

文檔地址:MyBatisPlus代碼生成器整合

MyBatis-Plus 從 3.0.3 之后移除了代碼生成器與模板引擎的默認依賴,需要手動添加相關依賴:

  1. 添加代碼生成器依賴
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.0</version>
</dependency>

八、ActiveRecord模式

  1. 實體類需要繼承Model類。
  2. mapper繼承BaseMapper。
  3. 可以將實體類作為方法的調用者。
    @Test
    public void selectById(){
        User user = new User();
        User selectById = user.selectById(1319899114158284802L);//新對象
        System.out.println(selectById == user); //false
        System.out.println(selectById);
    }

九、主鍵策略

博客地址:MybatisPlus的各種支持的主鍵策略!

十、MybatisPlus的配置

文檔地址:https://mybatis.plus/config/#基本配置

Springboot的使用方式

mybatis-plus:
  ......
  configuration:
    ......
  global-config:
    ......
    db-config:
      ......  

mapperLocations

  • 類型:String[]
  • 默認值:["classpath*:/mapper/**/*.xml"]

MyBatis Mapper 所對應的 XML 文件位置,如果您在 Mapper 中有自定義方法(XML 中有自定義實現),需要進行該配置,告訴 Mapper 所對應的 XML 文件位置。

Maven 多模塊項目的掃描路徑需以 classpath*: 開頭 (即加載多個 jar 包下的 XML 文件)

十一、通用Service

/**
 * Service接口,繼承IService
 * @author Summerday
 */
public interface UserService extends IService<User> {
}

/**
 * Service實現類,繼承ServiceImpl,實現接口
 * @author Summerday
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

}

@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTest {

    @Autowired
    UserService userService;

    /**
     * 鏈式查詢
     */
    @Test
    public void chain() {
        List<User> users = userService
                .lambdaQuery()
                .gt(User::getAge, 25)
                .like(User::getName, "雨")
                .list();
        for (User user : users) {
            System.out.println(user);
        }
    }

}

十二、邏輯刪除功能

博客地址:MybatisPlus的邏輯刪除功能使用!

十三、自動填充

博客地址:MybatisPlus的自動填充功能使用!

十四、樂觀鎖插件

博客地址:MybatisPlus的樂觀鎖插件使用!

十五、SQL分析打印

地址: 執行 SQL 分析打印,該插件有性能損耗,不建議生產環境使用。

  1. 引入maven依賴
<dependency>
  <groupId>p6spy</groupId>
  <artifactId>p6spy</artifactId>
  <version>最新版本</version>
</dependency>
  1. 配置application.yml
spring:
  datasource:
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver #p6spy 提供的驅動類
    url: jdbc:p6spy:mysql://localhost:3306/eblog?serverTimezone=GMT%2B8 #url 前綴為 jdbc:p6spy
    ...
  1. spy.properties配置
#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定義日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志輸出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系統記錄 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 設置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前綴
useprefix=true
# 配置記錄 Log 例外,可去掉的結果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 實際驅動可多個
#driverlist=org.h2.Driver
# 是否開啟慢SQL記錄
outagedetection=true
# 慢SQL記錄標准 2 秒
outagedetectioninterval=2

如何在控制台打印sql語句的執行結果?

<==    Columns: id, content, authorAvatar
<==        Row: 2, <<BLOB>>, /res/images/avatar/0.jpg
<==        Row: 1, <<BLOB>>, /res/images/avatar/default.png
<==      Total: 2

配置mybatis-plus.configuration.log-implorg.apache.ibatis.logging.stdout.StdOutImpl

十六、多租戶的使用

博客地址:MybatisPlus的多租戶插件使用!

十七、動態表名

添加配置 DynamicTableNameInnerInterceptor

@Configuration
@MapperScan("com.baomidou.mybatisplus.samples.dytablename.mapper")
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        HashMap<String, TableNameHandler> map = new HashMap<String, TableNameHandler>(2) {{
            put("user", (sql, tableName) -> {
                String year = "_2018";
                int random = new Random().nextInt(10);
                if (random % 2 == 1) {
                    year = "_2019";
                }
                return tableName + year;
            });
        }};
        dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        return interceptor;
    }
}

測試隨機訪問user_2018和user_2019

@SpringBootTest
class SampleTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    void test() {
        // 自己去觀察打印 SQL 目前隨機訪問 user_2018  user_2019 表
        for (int i = 0; i < 6; i++) {
            User user = userMapper.selectById(1);
            System.err.println(user.getName());
        }
    }
}

十八、sql注入器

博客地址:MybatisPlus的sql注入器使用!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM