Fluent Mybatis! Achieve the integration of code logic and sql logic

Using fluent mybatis, you can construct complex business sql statements through java api without writing specific xml files, so as to achieve the integration of code logic and sql logic. It is no longer necessary to assemble query or update operations in Dao, and reassemble parameters in xml or mapper. Compared with native Mybatis, Mybatis Plus or other frameworks, what convenience does fluent mybatis provide?

Scenario requirement settings

We realize and compare it through a typical business demand. If there is a student transcript, the structure is as follows:

 
create table `student_score`
(
    id           bigint auto_increment comment 'Primary key ID' primary key,
    student_id bigint            not null comment 'Student number',
    gender_man tinyint default 0 not null comment 'Gender, 0:female; 1:male',
    school_term int               null comment 'semester',
    subject varchar(30) null comment 'subject',
    score int               null comment 'achievement',
    gmt_create datetime not null comment 'Record creation time',
    gmt_modified datetime not null comment 'Record the last modification time',
    is_deleted tinyint default 0 not null comment 'Logical deletion ID'
) engine = InnoDB default charset=utf8;

Now there are needs:

According to the statistics, the passing scores of three subjects ('English ',' Mathematics' and 'Chinese') in 2000 are calculated according to the semester. The lowest, highest and average scores of the subjects are calculated, and the number of samples needs to be greater than 1. The statistical results are sorted according to the semester and discipline

We can write SQL statements as follows:

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 ('English', 'mathematics', 'language')
  and score >= 60
  and is_deleted = 0
group by school_term, subject
having count(score) > 1
order by school_term, subject;

The above requirements are implemented with fluent mybatis, native mybatis and Mybatis plus.

Comparison of the three

Use fluent mybatis to realize the above functions

We can see the ability of fluent api and the rendering effect of IDE on code.

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

Change to mybatis native to achieve the effect

1. Define Mapper interface

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

2. Define the parameter entity SummaryQuery required by the interface

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


3. Define the mapper xml file that implements the business logic

<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. Implement the business interface (here is the test class, which should correspond to Dao class in practical application)

@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("English", "mathematics", "language"))
            .setScore(60)
            .setMinCount(1);

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

In short, using mybatis directly, the implementation steps are quite cumbersome and the efficiency is too low. What is the effect of changing to mybatis plus?

Change to mybatis plus to achieve the effect

The implementation of mybatis plus is much simpler than that of mybatis. The implementation effects are as follows:

As circled in the red box, writing the mybatis plus implementation uses a lot of hard coding of strings (you can use the get lambda method of Entity to partially replace the string coding). Hard coding of strings will create a great threshold for development students. Personally, there are two main points:

1. Difficulty in memorizing and typing field names

2. The entity attribute follows the runtime error after the database field is changed

Other frameworks, such as TkMybatis, are weaker in encapsulation and ease of use than mybatis plus, so they are no longer compared.

Generate code code comparison

fluent mybatis generate code settings

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(
        /** Database connection information**/
        url = url, username = "root", password = "password",
        /** Entity Class parent package path**/
        basePack = "cn.org.fluent.mybatis.springboot.demo",
        /** Entity Code source directory**/
        srcDir = "spring-boot-demo/src/main/java",
        /** Dao Code source directory**/
        daoDir = "spring-boot-demo/src/main/java",
        /** If a table definition record is created, the record is modified, and the field is deleted logically**/
        gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted",
        /** Table to generate file (Table Name: corresponding Entity name)**/
        tables = @Table(value = {"student_score"})
    )
    static class Abc {
    }
}

mybatis plus code generation settings

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

After reading the implementation of the same function point in the three frameworks, you watchers will certainly have your own judgment. The author also summarizes a comparison here.

Author: rice straw Jiangnan

Link: Juejin cn/post/6886019929519177735

Added by Nile on Tue, 04 Jan 2022 07:14:21 +0200