最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Fluent Mybatis如何做到代碼邏輯和sql邏輯的合一

 更新時間:2021年08月04日 15:45:17   作者:、唐城  
對比原生Mybatis, Mybatis Plus或者其他框架,F(xiàn)luentMybatis提供了哪些便利呢?很多朋友對這一問題不是很清楚,今天小編給大家?guī)硪黄坛剃P(guān)于Fluent Mybatis如何做到代碼邏輯和sql邏輯的合一,一起看看吧

使用fluent mybatis可以不用寫具體的xml文件,通過java api可以構(gòu)造出比較復(fù)雜的業(yè)務(wù)sql語句,做到代碼邏輯和sql邏輯的合一。不再需要在Dao中組裝查詢或更新操作,在xml或mapper中再組裝參數(shù)。那對比原生Mybatis, Mybatis Plus或者其他框架,F(xiàn)luentMybatis提供了哪些便利呢?

場景需求設(shè)置

我們通過一個比較典型的業(yè)務(wù)需求來具體實(shí)現(xiàn)和對比下,假如有學(xué)生成績表結(jié)構(gòu)如下:

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

現(xiàn)在有需求:

統(tǒng)計(jì)2000年三門學(xué)科('英語', '數(shù)學(xué)', '語文')及格分?jǐn)?shù)按學(xué)期,學(xué)科統(tǒng)計(jì)最低分,最高分和平均分, 且樣本數(shù)需要大于1條,統(tǒng)計(jì)結(jié)果按學(xué)期和學(xué)科排序

我們可以寫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 ('英語', '數(shù)學(xué)', '語文')
  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來實(shí)現(xiàn)一番。

三者對比

使用fluent mybatis 來實(shí)現(xiàn)上面的功能

圖片

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

代碼:https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/master/spring-boot-demo/

換成mybatis原生實(shí)現(xiàn)效果

1. 定義Mapper接口

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

2. 定義接口需要用到的參數(shù)實(shí)體 SummaryQuery

@Data
@Accessors(chain = true)
public class SummaryQuery {
    private Integer schoolTerm;
    private List<String> subjects;
    private Integer score;
    private Integer minCount;
}

3. 定義實(shí)現(xiàn)業(yè)務(wù)邏輯的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. 實(shí)現(xiàn)業(yè)務(wù)接口(這里是測試類, 實(shí)際應(yīng)用中應(yīng)該對應(yīng)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("英語", "數(shù)學(xué)", "語文"))
            .setScore(60)
            .setMinCount(1);
 
        List<Map<String, Object>> summary = mapper.summaryScore(paras);
        System.out.println(summary);
    }
}

總之,直接使用mybatis,實(shí)現(xiàn)步驟還是相當(dāng)?shù)姆爆?,效率太低。那換成mybatis plus的效果怎樣呢?

換成mybatis plus實(shí)現(xiàn)效果

mybatis plus的實(shí)現(xiàn)比mybatis會簡單比較多,實(shí)現(xiàn)效果如下:

圖片

如紅框圈出的,寫mybatis plus實(shí)現(xiàn)用到了比較多字符串的硬編碼(可以用Entity的get lambda方法部分代替字符串編碼)。字符串的硬編碼,會給開發(fā)同學(xué)造成不小的使用門檻,個人覺的主要有2點(diǎn):

1. 字段名稱的記憶和敲碼困難

2. Entity屬性跟隨數(shù)據(jù)庫字段發(fā)生變更后的運(yùn)行時錯誤

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

生成代碼編碼比較

fluent mybatis生成代碼設(shè)置

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(
        /** 數(shù)據(jù)庫連接信息 **/
        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",
        /** 如果表定義記錄創(chuàng)建,記錄修改,邏輯刪除字段 **/
        gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted",
        /** 需要生成文件的表 ( 表名稱:對應(yīng)的Entity名稱 ) **/
        tables = @Table(value = {"student_score"})
    )
    static class Abc {
    }
}

mybatis plus代碼生成設(shè)置

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

圖片

看完3個框架對同一個功能點(diǎn)的實(shí)現(xiàn), 各位看官肯定會有自己的判斷,筆者這里也總結(jié)了一份比較。

圖片

作者:稻草江南

鏈接:juejin.cn/post/6886019929519177735

到此這篇關(guān)于Fluent Mybatis如何做到代碼邏輯和sql邏輯的合一的文章就介紹到這了,更多相關(guān)Fluent Mybatis代碼邏輯和sql邏輯的合一內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java集合類HashMap源碼解析

    java集合類HashMap源碼解析

    這篇文章主要介紹了Java集合之HashMap用法,結(jié)合實(shí)例形式分析了java map集合中HashMap定義、遍歷等相關(guān)操作技巧,需要的朋友可以參考下
    2021-06-06
  • IDEA如何將右下角提示框禁止彈出問題

    IDEA如何將右下角提示框禁止彈出問題

    這篇文章主要介紹了IDEA如何將右下角提示框禁止彈出問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • SpringBoot中Json工具類的實(shí)現(xiàn)

    SpringBoot中Json工具類的實(shí)現(xiàn)

    本文介紹在Java項(xiàng)目中實(shí)現(xiàn)一個JSON工具類,支持對象與JSON字符串之間的轉(zhuǎn)換,并提供依賴和代碼示例便于直接應(yīng)用,感興趣的可以了解一下
    2024-10-10
  • Spring使用注解更簡單的讀取和存儲對象的方法

    Spring使用注解更簡單的讀取和存儲對象的方法

    這篇文章主要介紹了Spring使用注解更簡單的讀取和存儲對象的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2023-07-07
  • java使用靜態(tài)關(guān)鍵字實(shí)現(xiàn)單例模式

    java使用靜態(tài)關(guān)鍵字實(shí)現(xiàn)單例模式

    這篇文章主要為大家詳細(xì)介紹了java使用靜態(tài)關(guān)鍵字實(shí)現(xiàn)單例模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • Java之單例設(shè)計(jì)模式示例詳解

    Java之單例設(shè)計(jì)模式示例詳解

    這篇文章主要介紹了Java之單例設(shè)計(jì)模式示例詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • ELK搭建線上日志收集系統(tǒng)

    ELK搭建線上日志收集系統(tǒng)

    ELK日志收集系統(tǒng)進(jìn)階使用,本文主要講解如何打造一個線上環(huán)境真實(shí)可用的日志收集系統(tǒng),有了它,你就可以和去服務(wù)器上撈日志說再見了
    2022-07-07
  • 小白也可以學(xué)會的Java NIO的Write事件

    小白也可以學(xué)會的Java NIO的Write事件

    剛開始對NIO的寫操作理解的不深,不知道為什么要注冊寫事件,何時注冊寫事件,為什么寫完之后要取消注冊寫事件,今天特地整理了本篇文章,需要的朋友可以參考下
    2021-06-06
  • java編碼IDEA主題推薦

    java編碼IDEA主題推薦

    在這篇文章中,我精選了幾個比較是和?Java?編碼的?IDEA?主題供小伙伴們選擇。另外,我自己用的是?One?Dark?theme?這款,有需要的朋友可以借鑒參考下,希望大家喜歡
    2022-01-01
  • SpringCloud集成Hystrix熔斷過程分步分解

    SpringCloud集成Hystrix熔斷過程分步分解

    通過hystrix可以解決雪崩效應(yīng)問題,它提供了資源隔離、降級機(jī)制、融斷、緩存等功能。接下來通過本文給大家分享SpringCloud集成Hystrix熔斷,感興趣的朋友一起看看吧
    2022-09-09

最新評論

安阳市| 陇西县| 巩留县| 宜阳县| 房产| 青川县| 青浦区| 昌江| 青神县| 鸡东县| 岳阳县| 封丘县| 达尔| 石阡县| 陇川县| 环江| 丰宁| 顺平县| 乌兰察布市| 静安区| 景德镇市| 惠东县| 桐柏县| 武宁县| 泰来县| 晋中市| 延川县| 尤溪县| 平顺县| 太白县| 徐闻县| 临朐县| 正安县| 衡南县| 鲁山县| 迁西县| 疏附县| 南丹县| 德庆县| 汉沽区| 谷城县|