Goodbye, MybatisPlus, Ali launches new ORM framework

Using fluent mybatis, you don't have to write specific xml files. You can construct more complex business sql statements through java api to achieve the integration of code logic and sql logic. You no longer need to assemble queries or update operations in Dao, or reassemble parameters in xml and mapper. Compared with native Mybatis, Mybatis Plus or other frameworks, what convenience does fluent mybatis provide?

Demand scenario 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 of passing scores of three subjects ('English ',' Mathematics' and 'Chinese') in 2000, the lowest score, the highest score and the average score are counted by semester, and the number of samples needs to be greater than 1. The statistical results are sorted by 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

If you need the specific demonstration code of this article, you can add my wechat: codedq, get it for free!

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

Change to mybatis native to achieve the effect

  1. Define Mapper interface

public interface MyStudentScoreMapper {
    List<Map<String, Object>> summaryScore(SummaryQuery paras);
}
  1. 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;
}
  1. 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>
  1. 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() {
        //  Construct query parameters
        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 results 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. It is difficult to remember and type field names

  2. The Entity property follows the runtime error after the database field has 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",
        /** Tables that need to generate files   (   Table name: the 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();
    }
}

FluentMybatis feature list

Comparison and summary of the three

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.

Netizens interested in Fluent Mybatis support you to read the official source code and find more new worlds!

Tags: Java Database SQL db

Posted on Sun, 05 Dec 2021 20:51:29 -0500 by scialom