Fluent Mybatis 牛逼!

举报
民工哥 发表于 2022/06/02 22:06:07 2022/06/02
【摘要】 点击下方“Java编程鸭”关注并标星 更多精彩 第一时间直达 使用fluent mybatis可以不用写具体的xml文件,通过java api可以构造出比较复杂的业务sql语句,做到代码逻辑和sql逻辑的合一。不再需要在Dao中组装查询或更新操作,在xml或mapper中再组装参数。那对比原生Mybatis, Mybatis ...

点击下方“Java编程鸭”关注并标星

更多精彩 第一时间直达

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

场景需求设置

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


   
  1. create table `student_score`
  2. (
  3.     id           bigint auto_increment comment '主键ID' primary key,
  4.     student_id bigint            not null comment '学号',
  5.     gender_man tinyint default 0 not null comment '性别, 0:女; 1:男',
  6.     school_term int               null comment '学期',
  7.     subject varchar(30) null comment '学科',
  8.     score int               null comment '成绩',
  9.     gmt_create datetime not null comment '记录创建时间',
  10.     gmt_modified datetime not null comment '记录最后修改时间',
  11.     is_deleted tinyint default 0 not null comment '逻辑删除标识'
  12. ) engine = InnoDB default charset=utf8;

现在有需求:

统计2000年三门学科('英语', '数学', '语文')及格分数按学期,学科统计最低分,最高分和平均分, 且样本数需要大于1条,统计结果按学期和学科排序

我们可以写SQL语句如下:


   
  1. select school_term,
  2.        subject,
  3.        count(score) as count,
  4.        min(score) as min_score,
  5.        max(score) as max_score,
  6.        avg(score) as max_score
  7. from student_score
  8. where school_term >= 2000
  9.   and subject in ('英语''数学''语文')
  10.   and score >= 60
  11.   and is_deleted = 0
  12. group by school_term, subject
  13. having count(score) > 1
  14. order by school_term, subject;

那上面的需求,分别用fluent mybatis, 原生mybatis 和 Mybatis plus来实现一番。

三者对比

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

6c24a4e214161079576632204bd9de42.png 图片

我们可以看到fluent api的能力,以及IDE对代码的渲染效果。

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

换成mybatis原生实现效果

1. 定义Mapper接口


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

\2. 定义接口需要用到的参数实体 SummaryQuery


   
  1. @Data
  2. @Accessors(chain = true)
  3. public class SummaryQuery {
  4.     private Integer schoolTerm;
  5.     private List<String> subjects;
  6.     private Integer score;
  7.     private Integer minCount;
  8. }

\3. 定义实现业务逻辑的mapper xml文件


   
  1. <select id="summaryScore" resultType="map" parameterType="cn.org.fluent.mybatis.springboot.demo.mapper.SummaryQuery">
  2.     select school_term,
  3.     subject,
  4.     count(score) as count,
  5.     min(score) as min_score,
  6.     max(score) as max_score,
  7.     avg(score) as max_score
  8.     from student_score
  9.     where school_term >= #{schoolTerm}
  10.     and subject in
  11.     <foreach collection="subjects" item="item" open="(" close=")" separator=",">
  12.         #{item}
  13.     </foreach>
  14.     and score >= #{score}
  15.     and is_deleted = 0
  16.     group by school_term, subject
  17.     having count(score) > #{minCount}
  18.     order by school_term, subject
  19. </select>

\4. 实现业务接口(这里是测试类, 实际应用中应该对应Dao类)


   
  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest(classes = QuickStartApplication.class)
  3. public class MybatisDemo {
  4.     @Autowired
  5.     private MyStudentScoreMapper mapper;
  6.     @Test
  7.     public void mybatis_demo() {
  8.         
  9.         SummaryQuery paras = new SummaryQuery()
  10.             .setSchoolTerm(2000)
  11.             .setSubjects(Arrays.asList("英语""数学""语文"))
  12.             .setScore(60)
  13.             .setMinCount(1);
  14.         List<Map<String, Object>> summary = mapper.summaryScore(paras);
  15.         System.out.println(summary);
  16.     }
  17. }

总之,直接使用mybatis,实现步骤还是相当的繁琐,效率太低。那换成mybatis plus的效果怎样呢?

换成mybatis plus实现效果

mybatis plus的实现比mybatis会简单比较多,实现效果如下:

f675db4e2142b43ea73d2b005cfd5657.png 图片

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

\1. 字段名称的记忆和敲码困难

\2. Entity属性跟随数据库字段发生变更后的运行时错误

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

生成代码编码比较

fluent mybatis生成代码设置


   
  1. public class AppEntityGenerator {
  2.     static final String url = "jdbc:mysql://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8";
  3.     public static void main(String[] args) {
  4.         FileGenerator.build(Abc.class);
  5.     }
  6.     @Tables(
  7.         /** 数据库连接信息 **/
  8.         url = url, username = "root", password = "password",
  9.         /** Entity类parent package路径 **/
  10.         basePack = "cn.org.fluent.mybatis.springboot.demo",
  11.         /** Entity代码源目录 **/
  12.         srcDir = "spring-boot-demo/src/main/java",
  13.         /** Dao代码源目录 **/
  14.         daoDir = "spring-boot-demo/src/main/java",
  15.         /** 如果表定义记录创建,记录修改,逻辑删除字段 **/
  16.         gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted",
  17.         /** 需要生成文件的表 ( 表名称:对应的Entity名称 ) **/
  18.         tables = @Table(value = {"student_score"})
  19.     )
  20.     static class Abc {
  21.     }
  22. }

mybatis plus代码生成设置


   
  1. public class CodeGenerator {
  2.     static String dbUrl = "jdbc:mysql://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8";
  3.     @Test
  4.     public void generateCode() {
  5.         GlobalConfig config = new GlobalConfig();
  6.         DataSourceConfig dataSourceConfig = new DataSourceConfig();
  7.         dataSourceConfig.setDbType(DbType.MYSQL)
  8.             .setUrl(dbUrl)
  9.             .setUsername("root")
  10.             .setPassword("password")
  11.             .setDriverName(Driver.class.getName());
  12.         StrategyConfig strategyConfig = new StrategyConfig();
  13.         strategyConfig
  14.             .setCapitalMode(true)
  15.             .setEntityLombokModel(false)
  16.             .setNaming(NamingStrategy.underline_to_camel)
  17.             .setColumnNaming(NamingStrategy.underline_to_camel)
  18.             .setEntityTableFieldAnnotationEnable(true)
  19.             .setFieldPrefix(new String[]{"test_"})
  20.             .setInclude(new String[]{"student_score"})
  21.             .setLogicDeleteFieldName("is_deleted")
  22.             .setTableFillList(Arrays.asList(
  23.                 new TableFill("gmt_create", FieldFill.INSERT),
  24.                 new TableFill("gmt_modified", FieldFill.INSERT_UPDATE)));
  25.         config
  26.             .setActiveRecord(false)
  27.             .setIdType(IdType.AUTO)
  28.             .setOutputDir(System.getProperty("user.dir") + "/src/main/java/")
  29.             .setFileOverride(true);
  30.         new AutoGenerator().setGlobalConfig(config)
  31.             .setDataSource(dataSourceConfig)
  32.             .setStrategy(strategyConfig)
  33.             .setPackageInfo(
  34.                 new PackageConfig()
  35.                     .setParent("com.mp.demo")
  36.                     .setController("controller")
  37.                     .setEntity("entity")
  38.             ).execute();
  39.     }
  40. }
1c145d248cb1e5462ce8a93d5ea123c7.png 图片

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

21433648cc14725b3bc17275fb21c1b6.png
 
 
 
 
 
 
 
 

END


   
  1. 看完本文有收获?请转发分享给更多人
  2. 关注「Java编程鸭」,提升Java技能
  3. 关注Java编程鸭微信公众号,后台回复:码农大礼包 可以获取最新整理的技术资料一份。涵盖Java 框架学习、架构师学习等!
  4. 文章有帮助的话,在看,转发吧。
  5. 谢谢支持哟 (*^__^*)

文章来源: mingongge.blog.csdn.net,作者:民工哥,版权归原作者所有,如需转载,请联系作者。

原文链接:mingongge.blog.csdn.net/article/details/125093295

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。