首页 > 其他分享 >干掉 XML、Mapper,Fluent Mybatis 牛逼

干掉 XML、Mapper,Fluent Mybatis 牛逼

时间:2024-05-27 09:32:34浏览次数:13  
标签:XML Mapper school term fluent score mybatis new Fluent

干掉 XML、Mapper,Fluent Mybatis 牛逼


前言

使用fluent mybatis可以不用写具体的xml文件,通过java api可以构造出比较复杂的业务sql语句,做到代码逻辑和sql逻辑的合一。不再需要在Dao中组装查询或更新操作,在xml或mapper中再组装参数。那对比原生Mybatis, Mybatis Plus或者其他框架,FluentMybatis提供了哪些便利呢?


Part1仓库地址

详细的API及用法,可参考官方仓库

https://gitee.com/fluent-mybatis/fluent-mybatis

Part2需求场景设置

我们通过一个比较典型的业务需求来具体实现和对比下,假如有学生成绩表结构如下:

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来实现一番。

Part3三者实现对比

1使用fluent mybatis 来实现上面的功能

在这里插入图片描述
我们可以看到fluent api的能力,以及IDE对代码的渲染效果。

2换成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的效果怎样呢?

3换成mybatis plus实现效果

mybatis plus的实现比mybatis会简单比较多,实现效果如下
在这里插入图片描述
如红框圈出的,写mybatis plus实现用到了比较多字符串的硬编码(可以用Entity的get lambda方法部分代替字符串编码)。字符串的硬编码,会给开发同学造成不小的使用门槛,个人觉的主要有2点:

字段名称的记忆和敲码困难
Entity属性跟随数据库字段发生变更后的运行时错误

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


Part4生成代码编码比较

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

Part5FluentMybatis特性一览

在这里插入图片描述

Part6三者对比总结

看完3个框架对同一个功能点的实现, 各位看官肯定会有自己的判断,笔者这里也总结了一份比较。
在这里插入图片描述

标签:XML,Mapper,school,term,fluent,score,mybatis,new,Fluent
From: https://blog.csdn.net/qq_34901859/article/details/139225881

相关文章

  • xml获取数据
     获取xml文本加载xml文本解析xml文本:(1)获取根节点的所有字节点的list(2)将每个节点转换为xmlelement(3)从xmlelement中获取各种名称的数据//获取xml文件TextAssetxml=Resources.Load<TextAsset>(ConstPath.RDNameCfg);if(xml==null)......
  • 几种常用的配置文件格式对比分析——ini、json、xml、toml、yaml
    配置文件用于存储软件程序的配置信息,以便程序能够根据这些信息进行自定义和调整。常用的配置文件格式包括INI、XML、JSON和YAML。下面对它们进行简单介绍,并分析各自的优缺点。1.INI文件格式简介:INI(Initialization)文件是一种简单的配置文件格式,通常由节(section)、键(key)和......
  • python系列:Python3 XML处理模块详解
    Python3XML处理模块详解Python3XML处理模块详解一:XML文件格式二:ElementTree解析XML文件Element常用属性如下:1、tag2、attrib3、text4、childelements三:Element之查找四:Element之修改五:Element之删除六:Element之增加七:Element之排序Python3XML处理模块详解x......
  • VOC数据格式转YOLO(xml转txt)
            近日想训练yolov8模型,在网上找了很久公开数据集,好多都没有数据标注,好不容易找到一篇好的数据集,但是都是xml格式的,因此得想办法把xml格式转为yolo格式。    首先观察xml数据集格式:我圈出来比较重要的几条filename:就是xml标签所对应的图片的名字wid......
  • Java读取word文件 No valid entries or contents found, this is not a valid OOXML (
    有个项目涉及到了操作word文档,当我把一份未加密word文档放在项目resources目录下进行临时开发,读取这个word时报错:Causedby:org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException:Novalidentriesorcontentsfound,thisisnotavalidOOXML(OfficeOpenXML......
  • XML Schema 字符串数据类型及约束详解
    字符串数据类型用于包含字符字符串的值。字符串数据类型可以包含字符、换行符、回车符和制表符。以下是模式中字符串声明的示例:<xs:elementname="customer"type="xs:string"/>您文档中的一个元素可能如下所示:<customer>JohnSmith</customer>或者可能是这样的:<custome......
  • XML Schema 字符串数据类型及约束详解
    字符串数据类型用于包含字符字符串的值。字符串数据类型可以包含字符、换行符、回车符和制表符。以下是模式中字符串声明的示例:<xs:elementname="customer"type="xs:string"/>您文档中的一个元素可能如下所示:<customer>JohnSmith</customer>或者可能是这样的:<c......
  • mapper,service,controller,entity之间的关系
    目录一、学到了二、错误与纠正一、学到了1.mapper(repository):数据访问层,负责与数据库进行交互,执行数据库的操作。定义了各种数据库操作方法的接口,并由ORM框架自动实现主要职能是执行数据库的增删改查,并将数据库操作结果返回给上层的service。2.service:业务逻辑层,处理逻......
  • spring-xml文件头
    1.beans<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.sp......
  • 在Flink中jackson-databind包下的ObjectMapper处理大写字段问题
    需要加上配置,不然解析会失败,产生一个空对象objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES,true);//忽略大小写代码:publicclassStreamingJob{publicstaticvoidmain(String[]args)throwsException{finalLoggerlogger......