[Open Source and Project Combat: Open Source Combat] 87 | Open source combat five (on): How does MyBatis weigh ease of use, performance and flexibility?

In the last few lessons, we talked about the Spring framework, analyzed some general design ideas behind it, and used more than a dozen design patterns. Starting today, let's analyze another framework that is often used in Java project development: MyBatis. Because the content is more, similarly, we also divide it into three classes to explain.

  • In the first lesson, we analyze how MyBatis weighs the ease of use, performance and flexibility of the code.
  • In the second lesson, we learn how to implement MyBatis Plugin using the responsibility chain and proxy mode.
  • In the third lesson, we summarize and list more than a dozen design patterns used in the MyBatis framework.

Without further ado, let's officially start today's study!

Introduction to Mybatis and ORM Framework

Students who are familiar with Java should know that MyBatis is an ORM (Object Relational Mapping, object-relational mapping) framework. The ORM framework is mainly based on the mapping relationship between classes and database tables to help programmers automatically realize the mutual conversion between objects and data in the database. To be more specific, ORM is responsible for storing the objects in the program in the database and converting the data in the database into objects in the program. In fact, there are many ORM frameworks in Java, in addition to MyBatis just mentioned, there are Hibernate, TopLink and so on.

When analyzing the Spring framework, we said that if we use one sentence to summarize the role of the framework, it is to simplify development. The MyBatis framework is no exception. What it simplifies is the development of the database. So how does MyBatis simplify database development? Let's illustrate it with the example of JdbcTemplate in the 59th lecture.

In Lecture 59, we mentioned that Java provides the JDBC class library to encapsulate different types of database operations. However, it is still a bit troublesome to use JDBC directly for database programming. Therefore, Spring provides JdbcTemplate, which further encapsulates JDBC to further simplify database programming.

Using JdbcTemplate for database programming, we only need to write business-related codes (such as SQL statements, codes for mutual conversion between data and objects in the database), and other process-related codes (such as loading drivers, creating database connections, Create a statement, close the connection, close the statement, etc.) are encapsulated in the JdbcTemplate class, we do not need to write repeatedly.

At that time, in order to show how using JdbcTemplate simplifies database programming, we also gave an example of querying user information in the database. Still the same example, let me see how to use MyBatis to achieve it, is it simpler than using JdbcTemplate.
Because MyBatis depends on the JDBC driver, to use MyBatis in the project, in addition to the introduction of the MyBatis framework itself (mybatis.jar), it is also necessary to introduce the JDBC driver (for example, to access MySQL's JDBC driver implementation class library mysql-connector-java. jar). After introducing the two jar packages into the project, we can start programming. The code for using MyBatis to access user information in the database is as follows:

// 1. 定义UserDO
public class UserDo {
  private long id;
  private String name;
  private String telephone;
  // 省略setter/getter方法
}
// 2. 定义访问接口
public interface UserMapper {
  public UserDo selectById(long id);
}
// 3. 定义映射关系:UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.xzg.cd.a87.repo.mapper.UserMapper">
    <select id="selectById" resultType="cn.xzg.cd.a87.repo.UserDo">
        select * from user where id=#{id}
    </select>
</mapper>
// 4. 全局配置文件: mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" />
                <property name="username" value="root" />
                <property name="password" value="..." />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>

It should be noted that in the UserMapper.xml configuration file, we only defined the mapping relationship between the interface and the SQL statement, and did not explicitly define the mapping relationship between the class (UserDo) field and the database table (user) field . In fact, this embodies the design principle of "convention over configuration". The default mapping relationship is used between the class field and the database table field: the class field is mapped to the field with the same spelling in the database table one by one. Of course, if there is no way to do one-to-one mapping, we can also customize the mapping relationship between them.

With the above code and configuration, we can access the user information in the database as follows.

public class MyBatisDemo {
  public static void main(String[] args) throws IOException {
    Reader reader = Resources.getResourceAsReader("mybatis.xml");
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
    SqlSession session = sessionFactory.openSession();
    UserMapper userMapper = session.getMapper(UserMapper.class);
    UserDo userDo = userMapper.selectById(8);
    //...
  }
}

From the code, we can see that the implementation using MyBatis is more flexible than the implementation using JdbcTemplate. In the implementation using JdbcTemplate, the conversion code and SQL statement between the object and the data in the database are hard-coded in the business code. In the implementation using MyBatis, the mapping relationship between class fields and database fields, and the mapping relationship between interfaces and SQL is written in the XML configuration file, which is separated from the code, which will be more flexible and Clear and easier to maintain.

How to balance ease of use, performance and flexibility?

We just made a brief introduction to the MyBatis framework, and then, let's compare the other two frameworks: JdbcTemplate and Hibernate. By comparing us, how MyBatis weighs the ease of use, performance and flexibility of the code.

Let's look at JdbcTemplate first. Compared with MyBatis, JdbcTemplate is more lightweight. Because it only makes a very simple package for JDBC, so the performance loss is relatively small. Compared to the other two frameworks, it has the best performance. However, its shortcomings are also obvious, that is, SQL and code are coupled together, and it does not have the function of ORM. You need to write your own code to analyze the mapping relationship between objects and data in the database. Therefore, it is not as good as the other two frameworks in terms of ease of use.

Let's look at Hibernate again. Compared with MyBatis, Hibernate is more heavyweight. Hibernate provides a more advanced mapping function, which can automatically generate SQL statements according to business needs. We don't need to write SQL ourselves like we do with MyBatis. Therefore, sometimes, we also call MyBatis a semi-automated ORM framework, and Hibernate a fully automated ORM framework. However, although the automatic generation of SQL simplifies development, it is automatically generated after all without targeted optimization. In terms of performance, the resulting SQL may not be as well written as the programmer. At the same time, this also loses the flexibility of programmers to write SQL by themselves.

In fact, no matter which implementation method is used, the code logic involved in the process of fetching data from the database and converting it into objects is basically the same. The difference between different implementation methods is just which part of the code logic is placed where. Some frameworks provide more powerful functions, and most of the code logic is completed by the framework, and programmers only need to implement a small part of the code. This makes the framework easier to use. However, the more functions the framework integrates, the more additional processing code will be introduced for the commonality of processing logic. Compared with specific programming for specific problems, the performance loss is relatively large.

So, roughly speaking, sometimes, the ease of use and performance of the framework are in opposition. The pursuit of ease of use, the performance is worse. On the contrary, the pursuit of performance, ease of use is worse. Besides, the easier it is to use, the less flexible it is. This is like the camera we use. A point-and-shoot camera can take a picture by pressing the shutter, but it is not as flexible as a complicated SLR.
In fact, the frameworks of JdbcTemplate, MyBatis, and Hibernate also reflect the law just mentioned.

JdbcTemplate provides the simplest functions, the worst usability, the least performance loss, and the best programming performance with it. Hibernate provides the most complete functions and the best ease of use, but relatively speaking, the performance loss is the highest. MyBatis is in the middle of the two, and has achieved a trade-off in terms of ease of use, performance, and flexibility. It supports programmers to write SQL by themselves, and can continue the programmer's accumulation of SQL knowledge. Compared with Hibernate, which is completely black box, many programmers prefer the translucent framework of MyBatis. This also reminds us that over-encapsulation and over-simplified development methods will also lose the flexibility of development.

key review

Well, that's all for today's content. Let's summarize and review together, what you need to focus on.

If you are familiar with Java and MyBatis, then you should master the differences between JDBC, JdbcTemplate, MyBatis, and Hibernate today. JDBC is a development specification for Java to access databases. It provides a set of abstract and unified development interfaces and hides the access details of different databases.

JdbcTemplate, MyBatis, and Hibernate are all secondary packages of JDBC in order to further simplify database development. Among them, JdbcTemplate cannot be regarded as an ORM framework, because programmers need to program themselves to realize the mutual conversion between objects and database data. Compared with Hibernate, a fully automatic ORM framework that does not even require programmers to write SQL, MyBatis is a semi-automatic ORM framework.

If you are not familiar with Java and MyBatis, as a background introduction, you can simply understand MyBatis and ORM. However, there should be a corresponding ORM framework in the language you are familiar with, and you can also compare and analyze it.

In addition to providing a background introduction to MyBatis, today's content also learns the relationship between the ease of use, performance, and flexibility of the code. Generally speaking, the more advanced functions provided, the greater the performance loss; the easier it is to use and the simpler the development method provided, the lower the flexibility.

class disscussion

In your project development, have you used any frameworks that can actually improve development efficiency and reduce unnecessary manual labor?

Guess you like

Origin blog.csdn.net/qq_32907491/article/details/131497796