【java框架】MyBatis-Plus(1)--MyBatis-Plus快速上手開發及核心功能體驗


1.MyBatis-Plus入門開發及配置

1.1.MyBatis-Plus簡介

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

MyBatis-Plus易於學習,官網提供了基於SpringBoot的中文文檔,社區活躍,版本迭代快速。

MyBatis-Plus官方文檔:https://baomidou.com/guide/,可作為日常開發文檔及特性學習。

 

1.2.基於SpringBoot項目集成MyBatis-Plus

可以基於IDEA的Spring Initializr進行SpringBoot項目的創建,或者移步至Boot官網構建一個簡單的web starter項目:https://start.spring.io/

①導入MyBatis-Plus相關的依賴包、數據庫驅動、lombok插件包:

pom.xml 文件配置

<dependencies>
    <!--數據庫驅動-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!--lombok-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <!--mybatis-plus:版本3.0.5-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.0.5</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

 

②配置數據庫驅動、日志級別

application.properties配置

# mysql5 驅動不同,默認驅動:com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus_0312?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
#mysql8 驅動不同:com.mysql.cj.jdbc.Driver、需要增加時區的配置:serverTimezone=GMT%2B8,mysql8的驅動向下兼容mysql5
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

 

1.3.入門Hello World進行數據庫操作

基於官網示例來構建數據庫表單及POJO數據類:https://baomidou.com/guide/quick-start.html#初始化工程

MybatisPlusApplication啟動類:

@SpringBootApplication
//配置Mapper接口類掃描
@MapperScan("com.fengye.mapper")
//配置Spring Bean注解掃描
@ComponentScan(basePackages = "com.fengye.mapper")
public class MybatisPlusApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusApplication.class, args);
    }
}

 

UserMapper類:

@Repository //持久層注解,表示該類交給Springboot管理
public interface UserMapper extends BaseMapper<User> {
}

 

User類:

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

 

基礎CRUD操作:

@SpringBootTest
class MybatisPlusApplicationTests {

    @Autowired  //需要配置SpringBoot包掃描,否則此處使用@Autowired會報警告
    //@Resource
    private UserMapper userMapper;

    @Test
    void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<User> userList = userMapper.selectList(null);
        Assert.assertEquals(5, userList.size());
        userList.forEach(System.out::println);
    }

    @Test
    void testInsert(){
        System.out.println("----- insert method test ------");
        User user = new User();
        user.setName("楓夜愛學習");
        user.setAge(20);
        user.setEmail("241337663@qq.com");
        int insertId = userMapper.insert(user);
        System.out.println(insertId);
    }

    @Test
    void testUpdate(){
        System.out.println("----- update method test ------");
        User user = new User();
        user.setId(1370382950972436481L);
        user.setName("苞米豆最愛");
        user.setAge(4);
        user.setEmail("baomidou@github.com");
        int updateId = userMapper.updateById(user);
        System.out.println(updateId);
        System.out.println(user);
    }

    @Test
    void testDelete(){
        System.out.println("----- delete method test ------");
        int deleteId = userMapper.deleteById(1370386235364118529L);
        System.out.println(deleteId);
    }
}

 

1.3.主鍵生成策略配置

主鍵生成策略:

使用@TableId(type = IdType.AUTO,value = "id") ,value屬性值當實體類字段名和數據庫一致時可以不寫,這里的value指的是數據庫字段名稱,type的類型有以下幾種:

 

public enum IdType {
    AUTO(0),   //Id自增操作
    NONE(1),  //未設置主鍵
    INPUT(2),  //手動輸入,需要自己setID值
    ID_WORKER(3),  //默認的全局唯一id
    UUID(4),   //全局唯一id  uuid
    ID_WORKER_STR(5);  //ID_WORKER的字符串表示法
    ...
}

目前MyBatis-Plus官方文檔建議的id主鍵設置為:@TableId(type = IdType.INPUT)

 

1.4.自動填充

自動填充功能可以實現針對某個POJO類中的一些時間字段值進行自定義填充策略(非基於數據庫表設置timestamp默認根據時間戳更新),實現自動插入和更新操作:

①首先需要在POJO類上需要自動填充的字段上增加@TableField(fill = FieldFill.INSERT)、@TableField(fill = FieldFill.INSERT_UPDATE)注解:

@Data
public class User {
    //設置主鍵為需要自己填入設置
    @TableId(type = IdType.INPUT)
    private Long id;
    private String name;
    private Integer age;
    private String email;
    //當創建數據庫該字段時,自動執行創建該字段的默認值
    @TableField(fill = FieldFill.INSERT, value = "create_time")
    private Date createTime;
    //當數據庫該字段發生創建與更新操作時,自動去填充數據值
    @TableField(fill = FieldFill.INSERT_UPDATE, value = "update_time")
    private Date updateTime;
}

 

②自定義實現類MyMetaObjectHandler實現MetaObjectHandler接口,覆寫insertFill與updateFill方法:

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    //插入時的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        /**
         *  官網推薦--起始版本 3.3.0(推薦使用),本項目使用3.0.5版本
        this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
        this.strictUpdateFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now());
         */
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime",new Date(), metaObject);
    }

    //更新時的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        /**
         *  官方推薦-- 起始版本 3.3.0(推薦),本項目使用3.0.5版本
         * this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推薦)
         */
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

 

2.核心功能

2.1.批量查詢

// 測試批量查詢
@Test
public void testSelectByBatchId(){
    List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
    users.forEach(System.out::println);
}

 

2.2.分頁查詢

①需要在配置類中注冊分頁插件注解:

//注冊分頁插件
 @Bean
 public PaginationInterceptor paginationInterceptor() {
     PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
     // 設置請求的頁面大於最大頁后操作, true調回到首頁,false 繼續請求  默認false
     paginationInterceptor.setOverflow(false);
     return paginationInterceptor;
}

 

②測試分頁插件效果:

@Test
 public void testPageHelper(){
     //參數:當前頁;頁面大小
     Page<User> page = new Page<>(1, 2);
     userMapper.selectPage(page, null);
     List<User> records = page.getRecords();
     records.forEach(System.out::println);
     System.out.println("當前頁是:" + page.getCurrent());
     System.out.println("每頁顯示多少條數:" + page.getSize());
     System.out.println("總頁數是:" + page.getTotal());
 }

 

2.3.邏輯刪除

所謂邏輯刪除,在數據庫中並不是真正的刪除數據的記錄,而是通過一個變量來設置數據為失效狀態(deleted = 0 => deleted = 1)。使用場景:管理員登錄系統查看回收站被“刪除數據”。

在MybatisPlus中,給我們提供logicSqlInjector

邏輯刪除主要實現步驟:

①在數據庫中增加邏輯刪除字段deleted:

 

②實體類User中增加屬性字段,並添加@TableLogic注解:

@TableLogic  //邏輯刪除
private Integer deleted;

 

③注冊邏輯刪除組件:

 //注冊邏輯刪除插件
@Bean
public ISqlInjector sqlInjector(){
    return new LogicSqlInjector();
}

 

④在application.properties中配置邏輯刪除:

#配置邏輯刪除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

 

執行測試Sql分析可以看到,實際邏輯刪除並沒有刪除,而是通過修改deleted狀態為1,數據仍可以保存在數據庫中:

 

2.4.條件構造器Wapper

條件構造器就是Wrapper,就是一個封裝查詢條件對象,讓開發者自由的定義查詢條件,主要用於sql的拼接,排序或者實體參數等;

在實際使用中需要注意:

使用的參數是數據庫字段名稱,不是Java類屬性名

條件構造器的查詢方法有很多,可以封裝出比較復雜的查詢語句塊,這里羅列一些重要常用的查詢方法,更多詳細請查詢官網地址:

https://mp.baomidou.com/guide/wrapper.html#abstractwrapper 

Wrapper分類:

 

 測試如下:

    // isNotNull:非空查詢
    // ge:>= 判斷查詢
    @Test
    public void testQueryWrapper(){
        //查詢name不為空、並且郵箱不為空、並且年齡大於等於12
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .isNotNull("name")
                .isNotNull("email")
                .ge("age", 21);
        List<User> users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);
    }

    // eq:用於單個查詢where name = 'xxx'
    @Test
    public void testQueryOne(){
        //查詢姓名為Sandy的用戶
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "Sandy");
        User selectOne = userMapper.selectOne(queryWrapper);
        System.out.println(selectOne);
    }

    //between:介於...之間
    @Test
    public void testQueryBetween(){
        //查詢年齡在20 - 30歲之間的用戶
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("age", 25, 30);
        List<User> userList = userMapper.selectList(queryWrapper);
        userList.forEach(System.out::println);
    }

    //notLike、likeRight、likeLeft
    @Test
    public void testQueryLike(){
        //查詢姓名中不包含字母'e'並且郵箱以't'開頭的
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .notLike("name", 'e')
                .likeRight("email", 't');
        List<User> userList = userMapper.selectList(queryWrapper);
        userList.forEach(System.out::println);
    }

    //inSql:表示in 查詢id IN ( select id from user where id < 3 )
    @Test
    public void testInSql(){
        //查詢姓名中不包含字母'e'並且郵箱以't'開頭的
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("id", "select id from user where id < 3");

        List<Object> objects = userMapper.selectObjs(queryWrapper);
        objects.forEach(System.out::println);
    }

    @Test
    public void testOrderBy(){
        //查詢user按年齡排序
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("age");
        List<User> userList = userMapper.selectList(queryWrapper);
        userList.forEach(System.out::println);
    }

 

3.插件擴展

3.1.樂觀鎖插件

當我們在開發中,有時需要判斷,當我們更新一條數據庫記錄時,希望這條記錄沒有被別人更新,這個時候就可以使用樂觀鎖插件。

樂觀鎖的實現方式:

  • 取出記錄時,獲取當前的version;
  • 更新時,帶上這個version;
  • 執行更新時,set version = new version where version = oldversion;
  • 如果version不對,就更新失敗

具體實現步驟如下:

①數據庫新增樂觀鎖字段version,設置默認值為1:

 

②在實體類User中新增version字段:

@Version //樂觀鎖Version注解
private Integer version;

 

③注冊樂觀鎖主鍵:

//開啟事務
@EnableTransactionManagement
@Configuration //聲明此類是配置類
public class MyBatisplusConfig {
    // 注冊樂觀鎖插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}

 

④測試單線程多線程情況樂觀鎖是否執行更新update成功:

// 測試樂觀鎖單線程執行成功
@Test
public void testOptimisticLocker(){
    // 1、查詢用戶信息
    User user = userMapper.selectById(1L);
    // 2、修改用戶信息
    user.setName("fengye");
    user.setEmail("241337663@qq.com");
    // 3、執行更新操作
    userMapper.updateById(user);
}

// 測試樂觀鎖失敗!多線程下
@Test
public void testOptimisticLocker2(){
    // 線程 1
    User user = userMapper.selectById(1L);
    user.setName("fengye111");
    user.setEmail("241337663@qq.com");
    // 模擬另外一個線程執行了插隊操作
    User user2 = userMapper.selectById(1L);
    user2.setName("fengye222");
    user2.setEmail("241337663@qq.com");
    userMapper.updateById(user2);
    userMapper.updateById(user); // 如果沒有樂觀鎖就會覆蓋插隊線程的值!
}

 

3.2.性能分析插件

MyBatis-Plus提供的性能分析插件可以作為性能分析攔截器,用於輸出每條SQL語句及其執行時間。可以在開發測試時定量分析慢查詢的SQL語句,用於后期優化分析。

 

具體使用步驟:

①在MyBatis-PlusConfig類中配置SQL性能分析插件:

/**
  * SQL執行效率插件
  */
 @Bean
 @Profile({"dev","test"})// 設置 dev test 環境開啟,保證我們的效率
 public PerformanceInterceptor performanceInterceptor() {
     PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
     performanceInterceptor.setMaxTime(100); // ms設置sql執行的最大時間為100ms,如果超過了則不執行
     performanceInterceptor.setFormat(true); // 是否格式化代碼
     return performanceInterceptor;
 }

 

②配置插件運行環境為dev:

#設置開發環境為dev
spring.profiles.active=dev

 

③執行測試,可以看到sql已經format及實際執行sql語句的消耗時間:

 @Test
 public void testPerformance(){
     // 查詢全部用戶
     List<User> users = userMapper.selectList(null);
     users.forEach(System.out::println);
 }

 

3.3.代碼生成器

AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個模塊的代碼,極大的提升了開發效率。

具體使用步驟如下:

①使用代碼生成器(Mybatis-Plus3.1.1版本以下)需要添加velocity模板、Swagger配置:

 <!--添加velocity模板-->
 <dependency>
     <groupId>org.apache.velocity</groupId>
     <artifactId>velocity-engine-core</artifactId>
     <version>2.3</version>
     </dependency>
     <!--Swagger配置-->
     <dependency>
        <groupId>com.spring4all</groupId>
        <artifactId>spring-boot-starter-swagger</artifactId>
        <version>1.5.1.RELEASE</version>
        <scope>provided</scope>
 </dependency>

 

②編寫自動生成器類:

public class AutoGeneratorUtil {
    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();
       // 策略配置
        // 1、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setActiveRecord(true);  //是否開啟AR模式
        gc.setAuthor("fengye");
        gc.setOutputDir(projectPath+"/src/main/java");
        gc.setOpen(false);
        gc.setFileOverride(false); // 是否覆蓋
        gc.setServiceName("%sService"); // 設置生成的services接口的名字的首字母是否為I
        //gc.setIdType(IdType.ID_WORKER);
        //gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);
        //2、設置數據源
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus_0312?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dsc.setUsername("root");
        dsc.setPassword("admin");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);
        //3、包的配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("test");
        pc.setParent("com.fengye");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        //設置xml文件與mapper目錄同級
        pc.setXml("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);
        //4、策略配置
        StrategyConfig strategy = new StrategyConfig();
        //設置要映射的表名,支持多張表以逗號隔開
        strategy.setInclude("user", "t_dept", "t_employee");
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true); //使用lombok注解
        strategy.setRestControllerStyle(true);  //Restful風格
        strategy.setLogicDeleteFieldName("deleted");  //邏輯刪除名稱
        //5、自動填充配置
        TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
        TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmtCreate);
        tableFills.add(gmtModified);
        strategy.setTableFillList(tableFills);
        //6、樂觀鎖
        strategy.setVersionFieldName("version");strategy.setRestControllerStyle(true);
        strategy.setControllerMappingHyphenStyle(true); //設置映射地址支持下划線 localhost:8080/hello_id_2
     //7、表前綴、生成表對應的PoJo時去掉前綴t
     strategy.setTablePrefix("t_");
mpg.setStrategy(strategy); mpg.execute(); } }

 

本博客寫作參考文檔相關:

https://baomidou.com/guide/   

http://luokangyuan.com/mybatisplusxue-xi-bi-ji/ 

https://www.bilibili.com/video/BV17E411N7KN?p=16&spm_id_from=pageDriver

 

示例代碼已上傳至Github地址:

https://github.com/devyf/JavaWorkSpace/tree/master/mybatis_plus/mybatis_plus_quickstart


免責聲明!

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



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