Things you didn't know about MyBatis

Preface: The predecessor of MyBatis is iBatis, which is a data persistence layer framework. Encapsulation optimizes the process of ordinary JDBC, such as creating database connections, setting SQL statement parameters, executing SQL statements, transactions, result mapping, and resource release.

Things you didn't know about MyBatis

MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures and advanced mapping. It uses simple XML or annotations for configuration and primitive mapping to map POJOs and database records to each other.

MyBatis framework analysis DISCOVERY

We know that the most basic JDBC operations are the following seven steps:

(1) Load the JDBC driver

(2) Establish and obtain a database connection

(3) Create a JDBC Statement object

(4) Set the incoming parameters of the SQL statement

(5) Execute the SQL statement and get the result

(6) Process the execution result

(7) Release related resources

The creation, acquisition and release code of database connections can be reused, and it is unnecessary to create and close database connections for each operation, which wastes resources and affects performance. Using database connection pools can solve these problems very well. Since different connection pools may be used, such as the connection pool using DBCP, or the JNDI database connection pool using the container itself, it can be decoupled through DataSource.

The MyBatis database connection pool configuration code managed by the Spring container is as follows:

<bean id = "dataSource" class = "org.springframework.jndi.JndiObjectFactoryBean">

<property name="jndiName" value = "${DB_JNDI_NAME}"></property>

</bean>

<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="datasource" />

<property name="configLocation" value="classpath:/config/mybatisConfig.xml"/>

</bean>

When basic JDBC operates the database, it assembles SQL statements in Java classes for execution. In order to be easier to use and higher performance, MyBatis also uses handwritten SQL instead of automatically generating SQL through complex configuration (the persistence frameworks of these two methods are commonly known as "semi-automatic" and "full-automation", MyBatis is " The leader of "semi-automation", and the representative of "full-automation" is hibernate. Both of these two persistence frameworks are very popular, and each has its own strengths, which can be appropriately applied according to needs). Putting SQL in a Java class will cause a lot of trouble. First, the readability is too poor, and it is not conducive to maintenance and reuse if it is scattered in various Java classes. Second, the Java code needs to be recompiled and deployed. Therefore, a unified file is required to store the relevant SQL.

XML files can customize tags, and can use #{parameter name} placeholders to identify parameters, and can introduce tags such as <if test=””></if> in JSTL to set dynamic SQL, so The ***Mapper.xml file is generally defined in MyBatis to save SQL. In data manipulation, a real Java object is required to undertake external calls. Therefore, the ***Mapper.xml file will have a corresponding ***Mapper.java interface file, and the framework exposes these Mapper objects to interface with the service layer.

MyBatis connects various operations through conventions and configurations. The method name in the Mapper.java class and the id of the SQL statement in Mapper.xml are defined to be the same for mapping; configure #{parameter name} to match the corresponding parameters. The returned result may be POJO, Map, List and other types, so we need to define the return result type clearly, and define the resultMap attribute value in the SQL statement; how to map the execution result and the data structure of the returned POJO object, in the Mapper.xml file You need to configure the mapped POJO objects and properties.

The three files Mapper.xml, Mapper.java and POJO objects complement each other. In business development, it is generally only necessary to add the contents of these three files. After the database connection and transaction configuration are structured, they will not change much. There are tools to generate these three files according to the table structure.

In general, the MyBatis framework defines Mapper objects to undertake external calls. The framework itself encapsulates SqlSession and SqlSessionFactory to connect to the database; it encapsulates StatementHandler and Executor to perform database operations; it encapsulates ResultSetHandler to process query results. We only need to structure the establishment method and transaction management of SqlSessionFactory, and provide Mapper objects according to the business. Mybatis combined with Spring container management is a good choice.

Some experiences in using MyBatisDISCOVERY

  1. Manual incremental configuration map file

    When there are tools to generate configuration files such as Mapper, many people are reluctant to write them manually. In fact, the generation tool of MyBatis is not particularly useful, and the generation method is almost unusable. And when you need to add or modify attributes and methods, you cannot use the generated files, because you need to keep some original attributes and methods. When handwriting the mapping file, define the fields used first, so that the configuration file will be concise and clear, and the result mapping will be more efficient.

  2. When the Mapper layer parameter is Map, the Service layer is responsible for overloading

    There are many similar methods in Mapper, which may query records according to fields, or query according to certain fields. Since it cannot be overloaded and in order to reduce redundant code, the parameters are generally set to Map. However, setting the parameter to Map will make the meaning of the code ambiguous, so overloading needs to be implemented at the service layer, and the service provided to the outside world is self-explanatory. Different service methods can be called according to the specific parameters.

  3. Minimize the use of statements such as if choose

    When configuring SQL in Mybatis, use if choose and other tags as little as possible, and try to use SQL to judge (CASE WHEN, DECODE, etc.) if you can use SQL to judge, which can improve query performance and facilitate maintenance.

Let's look at SQL like this:

SELECT * FROM USER WHERE

<choose>

<if test ="startdate != null and startdate != '' and enddate != null and enddate != '' ">

AND CREATE_DATE >= #{startdate} AND CREATE_DATE <= #{enddate}

</if>

<otherwise>

AND CREATE_DATE >= SYSDATE - 7 AND CREATE_DATE <= SYSDATE

</otherwise>

</choose >

Such an if judgment is actually completely unnecessary. We can simply use DECODE to solve the default value problem:

SELECT * FROM USER WHERE

CREATE_DATE >= DECODE(#{startdate},NULL,SYSDATE-7, #{startdate})

AND CREATE_DATE <= DECODE(#{enddate},NULL,SYSDATE,#{enddate})

However, it is impossible to completely remove the if and choose branches, but it is recommended to use the native SQL method to solve some dynamic problems, instead of relying entirely on Mybatis to complete the dynamic branch judgment, because the judgment branch is too complicated and difficult to maintain.

Want to develop this direction or really interested. You can come to me for learning materials, group number: 650385180, this is free, I hope that students will not take a reasonable attitude when they ask me for it, after all, it is my hard work, I hope you really have someone who wants to learn java well Heart, I will do my best to help you become a good programmer.

Note: Friends who like can like and add a wave of attention to learn and progress together

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325124443&siteId=291194637