好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Fluent Mybatis如何做到代码逻辑和sql逻辑的合一

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

场景需求设置

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

?

1

2

3

4

5

6

7

8

9

10

11

12

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语句如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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接口

?

1

2

3

public interface mystudentscoremapper {

     list<map<string, object>> summaryscore(summaryquery paras);

}

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

?

1

2

3

4

5

6

7

8

@data

@accessors (chain = true )

public class summaryquery {

     private integer schoolterm;

     private list<string> subjects;

     private integer score;

     private integer mincount;

}

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<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类)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@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点:

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

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

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

生成代码编码比较

fluent mybatis生成代码设置

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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代码生成设置

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

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个框架对同一个功能点的实现, 各位看官肯定会有自己的判断,笔者这里也总结了一份比较。

作者:稻草江南

链接:juejin.cn/post/6886019929519177735

到此这篇关于fluent mybatis如何做到代码逻辑和sql逻辑的合一的文章就介绍到这了,更多相关fluent mybatis代码逻辑和sql逻辑的合一内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/qq_41570658/article/details/119327923

查看更多关于Fluent Mybatis如何做到代码逻辑和sql逻辑的合一的详细内容...

  阅读:19次