[Spring Boot] Using XML configuration files to implement database operations (1)

Using XML configuration files to implement database operations (1)

1.SQL mapping file

The SQL mapping file is what we usually call mapper.

1.1 Structure of mapper.xml

Let’s introduce the structure of mapper.xml file in detail. First look at a complete mapper.xml example:

<?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="com.example.demo.Mapper.StudentMapper">
    <select id="selectAll" resultMap="BaseResultMap">
        SELECT
        *
        FROM student
    </select>

    <resultMap id="BaseResultMap" type="com.example.demo.model.Student">
        <id column="id" property="id" jdbcType="BIGINT" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="sex" property="sex" javaType="INTEGER" />
        <result column="age" property="age" jdbcType="INTEGER" />
    </resultMap>
</mapper>

As shown in the above example, generally mapper.xml is mainly divided into 4 parts:

1) The syntax declaration of mapper.xml declares the MyBatis syntax.

2) Specify the Mapper interface corresponding to the mapper.xml file through namespace.

3) Define the SQL statement corresponding to the interface method through XML tags, the id attribute corresponds to the method in the Mapper interface, and the resultMap attribute is the return value type.

4) <resultMap>The label defines the correspondence between the returned result type and the database table structure. The above mapping is the Student entity class object.

1.2 Tags of mapper.xml

The mapper.xml mapping file provides some very practical tags, among which the more commonly used tags include resultMap, sql, insert, update, delete, select and other tags. Be proficient in the use of tags, so that you can use MyBatis like a fish in water. MyBatis tags and function descriptions are shown in the table.

Insert image description here

2. Define SQL statements

MyBatis provides four tags: insert, update, delete and delete to define SQL statements. Next, we will introduce the usage of each tag starting from the SQL statement.

2.1 select

Select is one of the commonly used elements in MyBatis. MyBatis has made considerable improvements in query and result mapping. The select element of a simple query is very simple, such as:

<select id="selectOne" resultType="hashmap" parameterType="Long">
    SELECT name,age FROM student WHERE id = #{
    
    id}
</select>

In the above example, the student's name and age are queried by id. The defined method is named selectOne, receives a Long type parameter, and returns a HashMap type object. The key of HashMap is the column name, and the value is the corresponding value in the result set. #{id} is the parameter symbol passed in.

The select tag allows you to configure many attributes to configure the behavioral details of each statement, such as parameter type, return value type, etc. The included attributes are shown in the table.

Attributes illustrate
id The unique identifier in the namespace used to reference this statement
parameterType The data type of the parameters to be passed into the statement, optional. Because MyBatis can infer the data type of the parameters passed in the statement through the type handler (TypeHandler), the default value is unset (unset)
resultType The data type of the returned result. Note that if a collection is returned, it should be set to the type contained in the collection, not the type of the collection itself. Only one between resultType and resultMap can be used
resultMap Result mapping, resultMap is one of the powerful features of MyBatis, only one can be used between resultType and resultMap
flushCache Whether to clear the cache. The default value of the Select statement is false. If set to true, as long as the statement is called, the local cache and the second-level cache will be cleared.
useCache Whether to use cache, the default value is tue, cache the query results of this statement
timeout Timeout, the time to wait for the database to return the request result. The default value is unset
fetchSize Set the number of result rows to return. The default value is unset
statementType Use Statement, PreparedStatement or CallableStatement to execute SQL statements. The default value is PREPARED
resultSetType FORWARD_ONLY, SCROLL_SENSITIVE, SCROLL_INSENSITIVE or DEFAULT (equivalent to unset), the default value is DEFAULT
databaseId Database vendor identification (databaseldProvider). If this attribute is configured, MyBatis will load all statements without databaseId or matching the current databaseId.
resultOrdered For nested result select statements, the default value is false. If true, it will be assumed to contain nested result sets or groups. When a main result row is returned, no reference to the previous result set will be generated.
resultSets Applies only to multiple result sets. Lists the result sets returned after the statement is executed and gives each result set a name. Multiple names are separated by commas.

Although the select tag has many attributes, the four most commonly used attributes are id, parameterType, resultType, and resultMap. It should be noted that resultMap is one of the powerful features of MyBatis. If you understand it thoroughly, many complex mapping problems can be easily solved.

2.2 insert

The insert tag is mainly used to define SQL statements for inserting data, for example:

<insert id="insert" parameterType="com.example.demo.Mapper.Student">
    INSERT INTO
    student
    (id, name, sex, age)
    VALUES
    (#{
    
    id}, #{
    
    name}, #{
    
    sex}, #{
    
    age})
</insert>

In the above example, the configuration rules for the insert statement are more complex, and additional attributes and sub-elements are provided to handle how the primary key is generated.

If the database contains fields that automatically generate primary keys, you can set useGeneratedKeys="true" and then set keyProperty to the target property. For example, the Student table above has used an automatically generated primary key on the id column, then the statement can be modified as:

<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.example.demo.model.Student">
    INSERT INTO
    student
    (name, sex, age)
    VALUES
    (#{
    
    name}, #{
    
    sex}, #{
    
    age})
</insert>

In the above example, set useGeneratedKeys="true", and then set keyProperty="id" to the corresponding primary key field.

The attributes contained in the insert tag are shown in the table.

Attributes illustrate
id The unique identifier in the namespace used to reference this statement
parameterType The data type of the parameters to be passed into the statement, optional. MyBatis can infer the data type of the parameters passed in the statement through the type handler (TypeHandler). The default value is unset.
flushCache Whether to clear the cache. The default value is true. As long as the statement is called, the local cache and the second-level cache will be cleared.
timeout Timeout, which is the time to wait for the database to return the request result. The default value is unset
statementType Use Statement, PreparedStatement or CallableStatement to execute SQL statements. The default value is PREPARED
useGeneratedKeys Automatically generate the primary key. The default value is false. When set to true, the primary key is automatically generated according to the rules.
keyProperty Specify attributes that uniquely identify the object
keyColumn Specify the primary key column name of the database table
databaseld Database vendor identification (databaseIdProvider). If this attribute is configured, MyBatis will load all statements without databaseId or matching the current databaseId.

Commonly used attributes include id, parameterType, useGeneratedKeys, keyProperty, etc. Some attributes are consistent with the select tag.

2.3 update

The update tag is similar to the insert tag and is mainly used to map update statements. The sample code is as follows:

<update id="update" parameterType="com.example.demo.model.Student">
    UPDATE
    student
    SET
    name = #{
    
    name},
    sex = #{
    
    sex},
    age = #{
    
    age}
    WHERE
    id = #{
    
    iid
</update>

If you need to dynamically determine whether to make modifications based on the parameters passed in, you can use the if tag to dynamically generate SQL statements. The sample code is as follows:

<update id="update" parameterType="com.example.demo.model.Student">
    UPDATE
    student
    SET
    <if test="name != null">name = #{
    
    name},</if>
    <if test="sex != null">sex = #{
    
    sex},</if>
    age = #{
    
    age}
    WHERE
    id = #{
    
    iid
</update>

In the above example, the if tag is used to determine whether the incoming name parameter is empty, and SQL statements are dynamically generated based on the parameters.

The attributes contained in the update tag are basically the same as those of the insert tag.

2.4 delete

The delete tag is used to map delete statements.

<delete id="delete" parameterType="Long">
    DELETE FROM
    student
    WHERE
    id = #{
    
    id}
</delete>

The attributes contained in the delete tag are shown in the table.

Insert image description here

The delete tag is the same as the insert and update tags except that it lacks three attributes: useGeneratedKeys, keyProperty and keyColumn.

3. Result mapping

Result mapping is one of the important functions of MyBatis. For simple SQL queries, use the resultType attribute to automatically convert results to Java data types. However, if it is a complex statement, use resultMap mapping to convert the query results into data entity relationships.

3.1 resultType

When introducing the select tag earlier, we mentioned that the return result of the select tag can use the two attributes resultMap and resultType to specify the mapping structure. Let's demonstrate the usage of resultType.

<select id="selectOne" resultType="com.example.demo.model.Student">
    select *
    from student
    where id =#{
    
    id}
</select>

By setting the resultType attribute, MyBatis will automatically convert the query result set into a Student entity object. Of course, if you only query some fields, you can return a HashMap, such as:

<select id="selectOne" parameterType="Long" resultType="hashmap">
    select name,age from student where id = #{
    
    id}
</select>

In the above statement, Mybatis will automatically map all columns into HashMap objects.

3.2 resultMap

In the daily development process, resultType is sufficient in most cases. However, using resultType requires that the database field and attribute field names are consistent, otherwise you have to use aliases, which makes the SQL statement complicated.

Therefore, MyBatis provides the resultMap tag to define the mapping relationship between SQL query result fields and entity attributes. The following demonstrates the use of resultMap.

First, define resultMap:

<resultMap id="BaseResultMap" type="com.example.demo.model.Student">
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="sex" property="sex" javaType="INTEGER" />
    <result column="age" property="age" jdbcType="INTEGER" />
</resultMap>

In the above example, we use the resultMap tag to define the BaseResultMap mapping relationship to map the fields in the database to Student entity objects.

Then, use the customized BaseResultMap mapping relationship in the SQL statement and set the resultMap="BaseResultMap" of the select tag. The sample code is as follows:

<select id="selectOne" parameterType="Long" resultMap="BaseResultMap">
    SELECT
    *
    FROM student
    WHERE id =#{
    
    id}
</select>

3.3 Structure of resultMap

The structure of the resultMap tag is relatively complex and contains many sub-attributes and sub-tags. The resultMap tag contains id and type attributes:

  • id defines the unique identifier of the resultMap.
  • type is the class name of the return value.

Similarly, resultMap can also contain multiple sub-tags, including:

1) The id tag is used to set the mapping relationship between the primary key field and the domain model attribute. The primary key here is id, which corresponds to the primary key ID in the database field.

2) The result tag is used to set the attribute mapping relationship between ordinary fields and domain models.

3) The association tag is used to configure one-to-one result mapping, which can be associated with definitions in resultMap or references to other result mappings.

4) The collection tag is used to configure one-to-many result mapping, which can be associated with definitions in resultMap or references to other result mappings.

Below is the structure of the complete resultMap element:

<resultMap id="BaseResultMap" type="com.example.demo.model.Student">
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="sex" property="sex" javaType="INTEGER" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <association property="classes" javaType="com.example.demo.model.Classes">
        <id column="id" property="id"/>
        <result column="class_name" property="name" jdbcType="VARCHAR"/>
        <result column="memo" property="memo" jdbcType="VARCHAR"/>
    </association>
</resultMap>

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/132595593