1. 程式人生 > 其它 >取代MybatisPlus?阿里推出了新 ORM 框架!(兩者對比參考)

取代MybatisPlus?阿里推出了新 ORM 框架!(兩者對比參考)

使用fluent mybatis可以不用寫具體的xml檔案,通過java api可以構造出比較複雜的業務sql語句,做到程式碼邏輯和sql邏輯的合一。

不再需要在Dao中組裝查詢或更新操作,在xml或mapper中再組裝引數。

那對比原生Mybatis, Mybatis Plus或者其他框架,FluentMybatis提供了哪些便利呢?

需求場景設定

我們通過一個比較典型的業務需求來具體實現和對比下,假如有學生成績表結構如下:

create table `student_score`
(
    id           bigint auto_increment comment '主鍵ID' primary key,
    student_id   bigint            not 
null comment '學號', gender_man tinyint default 0 not null comment '性別, 0:女; 1:男', school_term int null comment '學期', subject varchar(30) null comment '學科', score int null comment '成績', gmt_create datetime not null comment '記錄建立時間', gmt_modified datetime not
null comment '記錄最後修改時間', is_deleted tinyint default 0 not null comment '邏輯刪除標識' ) engine = InnoDB default charset=utf8;

現在有需求:

統計2000年三門學科('英語', '數學', '語文')及格分數按學期,學科統計最低分,最高分和平均分, 且樣本數需要大於1條,統計結果按學期和學科排序

我們可以寫SQL語句如下

select school_term,
       subject,
       count(score) as count,
       min(score)   as min_score,
       max(score)   as max_score,
       avg(score)   as max_score
from student_score
where school_term 
>= 2000 and subject in ('英語', '數學', '語文') and score >= 60 and is_deleted = 0 group by school_term, subject having count(score) > 1 order by school_term, subject;

那上面的需求,分別用fluent mybatis, 原生mybatis 和 Mybatis plus來實現一番。

三者實現對比

使用fluent mybatis 來實現上面的功能

我們可以看到fluent api的能力,以及IDE對程式碼的渲染效果。

換成mybatis原生實現效果

1.定義Mapper介面

public interface MyStudentScoreMapper {
    List<Map<String, Object>> summaryScore(SummaryQuery paras);
}

2.定義介面需要用到的引數實體 SummaryQuery

@Data
@Accessors(chain = true)
public class SummaryQuery {
    private Integer schoolTerm;

    private List<String> subjects;

    private Integer score;

    private Integer minCount;
}

3.定義實現業務邏輯的mapper xml檔案

<select id="summaryScore" resultType="map" parameterType="cn.org.fluent.mybatis.springboot.demo.mapper.SummaryQuery">
    select school_term,
    subject,
    count(score) as count,
    min(score) as min_score,
    max(score) as max_score,
    avg(score) as max_score
    from student_score
    where school_term >= #{schoolTerm}
    and subject in
    <foreach collection="subjects" item="item" open="(" close=")" separator=",">
        #{item}
    </foreach>
    and score >= #{score}
    and is_deleted = 0
    group by school_term, subject
    having count(score) > #{minCount}
    order by school_term, subject
</select>

4.實現業務介面(這裡是測試類, 實際應用中應該對應Dao類)

@RunWith(SpringRunner.class)
@SpringBootTest(classes = QuickStartApplication.class)
public class MybatisDemo {
    @Autowired
    private MyStudentScoreMapper mapper;

    @Test
    public void mybatis_demo() {
        // 構造查詢引數
        SummaryQuery paras = new SummaryQuery()
            .setSchoolTerm(2000)
            .setSubjects(Arrays.asList("英語", "數學", "語文"))
            .setScore(60)
            .setMinCount(1);

        List<Map<String, Object>> summary = mapper.summaryScore(paras);
        System.out.println(summary);
    }
}

總之,直接使用mybatis,實現步驟還是相當的繁瑣,效率太低。那換成mybatis plus的效果怎樣呢?

換成mybatis plus實現效果

mybatis plus的實現比mybatis會簡單比較多,實現效果如下

如紅框圈出的,寫mybatis plus實現用到了比較多字串的硬編碼(可以用Entity的get lambda方法部分代替字串編碼)。

字串的硬編碼,會給開發同學造成不小的使用門檻,個人覺的主要有2點:

  • 欄位名稱的記憶和敲碼困難
  • Entity屬性跟隨資料庫欄位發生變更後的執行時錯誤

其他框架,比如TkMybatis在封裝和易用性上比mybatis plus要弱,就不再比較了。

生成程式碼編碼比較

fluent mybatis生成程式碼設定

public class AppEntityGenerator {
    static final String url = "jdbc:mysql://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8";

    public static void main(String[] args) {
        FileGenerator.build(Abc.class);
    }

    @Tables(
        /** 資料庫連線資訊 **/
        url = url, username = "root", password = "password",
        /** Entity類parent package路徑 **/
        basePack = "cn.org.fluent.mybatis.springboot.demo",
        /** Entity程式碼源目錄 **/
        srcDir = "spring-boot-demo/src/main/java",
        /** Dao程式碼源目錄 **/
        daoDir = "spring-boot-demo/src/main/java",
        /** 如果表定義記錄建立,記錄修改,邏輯刪除欄位 **/
        gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted",
        /** 需要生成檔案的表 ( 表名稱:對應的Entity名稱 ) **/
        tables = @Table(value = {"student_score"})
    )
    static class Abc {
    }
}

mybatis plus程式碼生成設定

public class CodeGenerator {

    static String dbUrl = "jdbc:mysql://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8";

    @Test
    public void generateCode() {
        GlobalConfig config = new GlobalConfig();
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)
            .setUrl(dbUrl)
            .setUsername("root")
            .setPassword("password")
            .setDriverName(Driver.class.getName());
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
            .setCapitalMode(true)
            .setEntityLombokModel(false)
            .setNaming(NamingStrategy.underline_to_camel)
            .setColumnNaming(NamingStrategy.underline_to_camel)
            .setEntityTableFieldAnnotationEnable(true)
            .setFieldPrefix(new String[]{"test_"})
            .setInclude(new String[]{"student_score"})
            .setLogicDeleteFieldName("is_deleted")
            .setTableFillList(Arrays.asList(
                new TableFill("gmt_create", FieldFill.INSERT),
                new TableFill("gmt_modified", FieldFill.INSERT_UPDATE)));

        config
            .setActiveRecord(false)
            .setIdType(IdType.AUTO)
            .setOutputDir(System.getProperty("user.dir") + "/src/main/java/")
            .setFileOverride(true);

        new AutoGenerator().setGlobalConfig(config)
            .setDataSource(dataSourceConfig)
            .setStrategy(strategyConfig)
            .setPackageInfo(
                new PackageConfig()
                    .setParent("com.mp.demo")
                    .setController("controller")
                    .setEntity("entity")
            ).execute();
    }
}

FluentMybatis特性一覽

三者對比總結

看完3個框架對同一個功能點的實現, 各位看官肯定會有自己的判斷,筆者這裡也總結了一份比較。

參考:https://mp.weixin.qq.com/s/EYhYfZ7JL0A6d6lyeZ833g