MyBatis framework construction and tutorial (detailed explanation)

MyBatis article directory
Mybatis framework construction and usage tutorials

Introduction

What is MyBatis?

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all JDBC code and the work of setting parameters and getting result sets. MyBatis can configure and map primitive types, interfaces and Java POJOs (Plain Old Java Objects) into records in the database through simple XML or annotations.

1. Steps to build MyBatis framework

1.1, Configuration XML

To use Maven to build the project, you need to place the following code in pom.xml:

        <!-- mysql 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>

        <!-- mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
1.2. Write the MyBatis framework core configuration file

The core configuration file of the MyBatis framework is mainly used to configure related information about connecting to the database and attributes that affect the runtime behavior of the MyBatis framework.

In order to facilitate classification management, a resources directory is often created in the project to store various configuration files. First right-click on the project to create a resource directory resources, as shown in the figure:
Insert image description here
Then right-click on the resources directory to create a new file and name it mybatis.xml.

Insert image description here

Then assign the following code to the mybatis.xml file.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--    引入jdbc.properties-->
    <properties resource="jdbc.properties"></properties>
<!--    配置mybatis的log实现为LOG4J-->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${pwd}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/xinxi2/dao/TSysUserMapper.xml"/>
        <mapper resource="com/xinxi2/dao/TSystorageMapper.xml"/>
    </mappers>
</configuration>

Finally, create a driver configuration file jdbc.properties for connecting to the database in the resources directory. Then assign the following code to jdbc.properties.

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/bianlidain?useUnicode=true&character
username=root
pwd=root
1.3. Create entity class

Create entity classes based on existing database

package com.xinxi2.bean;

public class Student {
    
    
    private int id;
    private String name;
    private int age;

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }
}

1.4, create Mapper interface

In the MyBatis framework, the Mapper interface refers to the interface used to bind to SQL mapping statements, also known as mapper, and is usually used in conjunction with SQL mapping files. For applications, the Mapper interface is the Dao interface, which defines the API for persisting data. Naming generally follows the rules of "instance class name" + Mapper. Generally placed under the Dao layer. As shown in the picture:

Insert image description here

The StudentMapper code is as follows:

package com.demo.dao;

import com.demo.bean.Student;

import java.util.List;

public interface StudentMapper {
    
    

    public List<Student> getlist();
}
1.5, create SQL mapping file

As shown in the picture:

Insert image description here

Defines a SQL mapping file related to user operations, which is an XML file. SQL mapping files are generally used in conjunction with the relevant Mapper interface. They belong to Dao components and are targeted at specific entity classes. Therefore, their naming rules are the same as those of the Mapper interface, which is "entity class name" + Mapper, and are usually placed in the same file as the Mapper interface. Bao Xia. Now create a StudentMapper.xml file in the dao package and copy the following content.

<?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.demo.dao.StudentMapper">

    <select id="getlist" resultType="com.demo.bean.Student">
        select * from student
    </select>
</mapper>

The meaning of each element is as follows:
mapper: the root element of the SQL mapping file, which has only one namespace attribute.
namespace: Namespace, used to organize and manage SQL mappings, realizes the isolation of SQL mappings, and the value should be globally unique.
select: Represents a query statement, one of the commonly used elements in the SQL mapping of the MyBatis framework. Some attributes are as follows:
id: The identifier of the SQL statement. The value is unique in the namespace and is generally the same as the interface name.
resultType: the return value type of the SQL statement.

Note that
the path information of the SQL mapping file needs to be added to the core configuration file mybatis-config.xml of the MyBatis framework. As shown in the following code:

    <mappers>
        <mapper resource="com/demo/dao/StudentMapper.xml"/>
    </mappers>
1.6, writing test classes

In order to facilitate test class management, we generally create a test folder in the project to store test-related code. Right-click the project to create the test folder, then right-click the test folder to create the test class. As shown in the picture:

Insert image description here

Then start writing code in this test class:

package com.demo.test;

import com.demo.bean.Student;
import com.demo.dao.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class test {
    
    

    public static void main(String[] args) {
    
    
        // 加载mybatis.xml文件
        String resource = "mybatis.xml";
        InputStream inputStream = null;
        SqlSession sqlSession = null;
        StudentMapper studentMapper = null;
        try {
    
    
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            // 开启事务,自动提交事务(无参--手动提交)
            sqlSession = sqlSessionFactory.openSession();
            studentMapper = sqlSession.getMapper(StudentMapper.class);
            List<Student> students = studentMapper.getlist();
            for (Student student1 : students) {
    
    
                System.out.println(student1.getName() + student1.getAge());
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            // 关闭sqlSession,从当前线程移除
            sqlSession.close();
        }
    }
}

The test code is as follows:

Insert image description here

2. Implementation method

2.1, SQL mapping xml file

The real feature of MyBatis is the SQL mapping statement, which is powerful and uses
several top-level elements of a simple SQL mapping file.

  • mapper
    • namespace attribute, distinguishes different mappers
    • The namespace and the id of the child element are jointly guaranteed to be unique
    • Bind DAO interface
    • The name of the namespace must have the same name as an interface
    • The methods in the interface correspond to the SQL statement ID in the mapping file one-to-one.
<mapper namespace="com.demo.dao.StudentMapper">

    <select id="getlist" .....>
        .......
    </select>
</mapper>
2.2, select tag
  • select is one of the most commonly used elements in MyBatis
  • The select element has many attributes, and each query statement can be configured in detail.
    • id
      • A unique identifier within a namespace
      • The methods in the interface correspond to the SQL statement ID in the mapping file one-to-one.
    • parameterType
      • Parameter type passed into the SQL statement
    • resultType
      • SQL statement returns the full class name or alias of the value type
<mapper namespace="com.demo.dao.StudentMapper">

    <select id="getlist" parameterType="int" resultType="com.demo.bean.Student">
        select * from student
    </select>
</mapper>
2.3, pass multiple parameters:
  1. Use Map to pass parameters
  2. Pass parameters using annotations
  3. Passing parameters using JavaBeans
2.4, insert tag:

The MyBatisinsert tag is used to define insert statements and perform insert operations. When MyBatis finishes executing an insert statement, it returns the number of rows it affected in the database.
In the StudentMapper.xml mapping file, add nodes and insert statements. The code is as follows

    <insert id="addStudent" useGeneratedKeys="true" keyProperty="id" keyColumn="id" parameterType="com.xinxi2.bean.Route">
        INSERT INTO route(`name`,`pwd`,`age`)
                values (#{name},#{pwd},#{age})
    </insert>

Define an addStudent() method in the StudentMapper interface, the code is as follows:

 int addStudent(Student student );

3. Dynamic SQL:

3.1, Overview:

Dynamic SQL is one of the powerful features of MyBatis. If you have used JDBC or other similar frameworks, you should understand how painful it is to splice SQL statements according to different conditions. For example, make sure not to forget to add necessary spaces when splicing, and be careful to remove the comma from the last column name in the list. Using dynamic SQL, you can completely get rid of this pain.

Working with dynamic SQL is not easy, but MyBatis makes this feature significantly easier to use with the powerful dynamic SQL language that can be used in any SQL mapped statement.

If you've used JSTL or any text processor based on an XML-like language before, dynamic SQL elements may seem familiar to you. In previous versions of MyBatis, it took time to understand a large number of elements. With the help of powerful OGNL-based expressions, MyBatis 3 has replaced most of the previous elements and greatly simplified the types of elements. Now the types of elements to learn are less than half of the original ones.

  1. if
  2. choose (when, otherwise)
  3. trim (where, set)
  4. foreach
3.2,if:

The if statement is simple to use and is often used in conjunction with the test attribute. The syntax is as follows:

<if test="判断条件">
  SQL语句
</if>
3.3, choose tag: multiple conditional branches:

Sometimes, we don't want to use all conditions, but just want to choose one from multiple conditions. For this situation, MyBatis provides the choose element, which is a bit like the switch statement in Java.

Dynamic statements in MyBatis are similar to switch-case-default multiple branch conditional statements in Java. Since MyBatis does not provide a corresponding else tag for if, if you want to achieve the effect of..., you can use,, to achieve it.

Dynamic statement,, syntax is as follows:

<choose>
    <when test="判断条件1">
        SQL语句1
    </when >
    <when test="判断条件2">
        SQL语句2
    </when >
    <when test="判断条件3">
        SQL语句3
    </when >
    <otherwise>
        SQL语句4
    </otherwise>
</choose>

Tags judge in order whether the judgment conditions in their internal tags are true. If one of them is true, the corresponding SQL statement is executed and the execution ends; if none of them are true, the SQL statement in progress is executed. This is similar to Java's switch statement, which is switch, case, and default.

3.4, where tag: processing query conditions:

If during the query process of multiple if conditions, if the condition 1=1 is not set in the where condition, it may become an incorrect statement like the following:

SELECT id,name,url,age,country FROM website AND name LIKE CONCAT('%',#{name},'%')

Obviously the above statement will cause SQL syntax exceptions, but adding a condition like "1=1" is very strange, so MyBatis provides the where tag. It is mainly used to simplify conditional judgment in SQL statements and can automatically handle AND/OR conditions. The syntax is as follows:

<where>
    <if test="判断条件">
        AND/OR ...
    </if>
</where>

When the judgment condition in the if statement is true, the where keyword will be added to the assembled SQL, otherwise it will not be added. where will retrieve the statement, and it will remove the AND or OR keyword of the first SQL conditional statement after where.

3.5, set tag: dynamic update:

In Mybatis, the update statement can use the set tag to dynamically update columns. The set tag can dynamically add the set keyword to the SQL statement and remove the extra commas appended to the end of the condition.

<update id="updateRoute" parameterType="com.xinxi2.bean.Route">
        update route
        <set>
            <if test="id!=null">
                id=#{id},
            </if>
            <if test="name!=null">
                `name`=#{name},
            </if>
            <if test="mileage!=null">
                mileage=#{mileage},
            </if>
        </set>
            where id=#{id}
    </update>
3.6, foreach tag: iterative traversal:

When the SQL statement contains the in keyword for list value matching and it is necessary to iterate the condition set to generate the condition, you can use foreach to implement the iteration of the SQL condition.

The Mybatis foreach tag is used for loop statements. It well supports collections of data and List and set interfaces, and provides traversal functions for this. The syntax format is as follows:

<foreach item="item" index="index" collection="list|array|map key" open="(" separator="," close=")">
    参数值
</foreach>

The foreach tag mainly has the following attributes, which are explained below.

  1. item: Represents the alias of each element in the collection when iterating.
  2. index: Specify a name to indicate the position of each iteration during the iteration process.
  3. open: Indicates what the statement starts with. Since it is an in conditional statement, it must start with (.
  4. separator: Indicates what symbol is used as the separator between each iteration. Since it is an in conditional statement, it must be used as the separator.
  5. close: Indicates what the statement ends with. Since it is an in conditional statement, it must end with ).
    When using the foreach tag, the collection attribute is required, but the value of this attribute is different in different situations. There are three main situations:
  6. If a single parameter is passed in and the parameter type is a List, the collection attribute value is list.
  7. If a single parameter is passed in and the parameter type is an array array, the attribute value of the collection is array.
  8. If there are multiple parameters passed in, they need to be encapsulated into a Map. Of course, a single parameter can also be encapsulated into a Map. The key of Map is the parameter name, and the collection attribute value is the key of the passed List or array object in its own encapsulated Map.

4. Related query:

4.1, Overview:

Association relationship is the concept of a database entity. There are three types of cascade relationships, namely one-to-one cascade, one-to-many cascade and many-to-many cascade. For example, a role can be assigned to multiple users, or to just one user. In most scenarios, we need to obtain role information and user information, so we often encounter the following SQL.

SELECT r.*,u.* FROM t_role r
INNER JOIN t_user_role ur ON r.id = ur.id
INNER JOIN t_user u ON ur.user_id = u.id
WHERE r.id = #{id}

There are three correspondences in the cascade.

  1. One-to-many , for example: roles and users, project teams and software engineers, users and shipping addresses.
  2. One-to-one , such as: product introduction and product details, basic student information and student status file information.
  3. Many-to-many , for example: orders and products, players and teams, for example: orders and products, players and teams
4.2, one-to-one related query:

One-to-one cascade relationships are very common in real life. For example, a student's basic information corresponds to a student status file.

In MyBatis, one-to-one cascading relationships are handled through the child elements of the element. The sample code is as follows:

<association property="studentCard" column="cardId"
            javaType="com.apesource.entity.StudentCard"
            select="com.apesource.mapper.StudentCardMapper.selectStuCardById" />

The following attributes are commonly used on elements.

  1. property: Specifies the object property mapped to the entity class.
  2. column: Specify the corresponding field in the table (that is, the column name returned by the query).
  3. javaType: Specifies the type mapped to entity object properties.
  4. select: Specify the sub-SQL statement that introduces the nested query. This attribute is used for nested queries in association mapping.
    One-to-one association queries can be used in the following two ways:
  5. Step-by-step query assigns values ​​to entity beans in a one-to-one relationship through two or more queries.
  6. Single-step query, implemented through associated query.
4.3. Many-to-many related query:

In actual applications, because the many-to-many relationship is relatively complex, it will increase the complexity of understanding and association, so it is rarely used. MyBatis does not implement many-to-many cascades. It is recommended to replace the many-to-many cascades with two one-to-many cascades to reduce the complexity of the relationship and simplify the program.

For example, an order can have multiple products, and one product can correspond to multiple orders. There is a many-to-many cascading relationship between orders and products. You can use an intermediate table (order record table) to convert the many-to-many cascade into two one-to-many relationships.

Guess you like

Origin blog.csdn.net/H20031011/article/details/131436266