MyBatis quick start and in-depth

table of Contents:

1. Build MyBatis environment

2. Configuration file

3. Mapping file

4. CURD operation [Getting started]

5. Tools CURD

6. Based on Mapper interface CURD

7. Concatenation


ORM:
     ORM (Object/Relational Mapping), that is, object/relational mapping.
    ORM is a general term for a type of framework, which completes the mapping of object data to relational data.
    Enables developers to operate databases with object-oriented thinking .

Common ORM frameworks:
     MyBatis, Hibernate, TopLink...


Meet MyBatis:


Concept:
     MyBatis is a Java-based persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. It
    was originally an open source project of apache-iBatis, and was migrated from apache to google in 2010 and was renamed MyBatis .
    in November 2013 migrated from google to GitHub


Features:
     1. MyBatis is a lightweight ORM framework that only needs mybatis-*.jar and a database driver to run.
    2. MyBatis avoids almost all JDBC code and manual setting of parameters and obtaining result sets
    3. Convert SQL code Separated from the program code, which is conducive to SQL reuse and modification
    4. MyBatis will not impose any influence on the design of the application or database, and improve the flexibility of the application

Summary: ORM is a type of framework, this type of framework is mainly used to operate the database, MyBatis belongs to the ORM type of framework, mainly used to simplify database operations and was born


The required jar package, click to download

Extraction code: 67xu


You can also go to the official website for relevant information and download

Official website

Download frame


Foreword: The most direct personal understanding of the framework is to write the code to complete certain functions, and package it into a jar package, provide the corresponding API, configuration information... for others to use


1. Build MyBatis environment

1.1 Add jar package

mybatis-3.5.1.jar
    mysql-connector-java-5.1.22-bin.jar

Note: This is used to operate the mysql database, so add the connection jar package for mysql data

1.2 Writing configuration files

Note: The name and location of the configuration file are not limited, but it is usually called mybatis-config.xml and stored under src

<?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="development">        <environment id="development">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <property name="driver" value="驱动器入口类的全名称"/>                <property name="url" value="url地址信息"/>                <property name="username" value="账户"/>                <property name="password" value="密码"/>            </dataSource>        </environment>    </environments>    <!--添加映射文件-->    <mappers>        <mapper resource="包名1/包名2/.../文件名.xml"/>    </mappers></configuration>

1.3 Writing the mapping file

<?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"><!--在当前XML中编写针对User的CURD操作命令--><mapper namespace="命名空间[类似包的作用]">    <select/insert/update/delete id="业务标记名" resultType="实体类全名" parameterType="占位符类型">        SQL命令    </select/insert/update/delete></mapper>

Remarks: The mapping file is used to realize the mapping relationship between entity objects and data table fields

(In layman's terms, the SQL statements for database operations should be written in the mapping file in the prescribed form and used through related naming calls)

1.4 Writing the startup program

    //获得MyBatis的配置文件: 数据库信息,映射文件信息[SQL]    InputStream is=Resources.getResourceAsStream("配置文件位置/配置文件名.xml");//参数为配置文件的位置: a/mybatis-config.xml    //基于配置信息创建SqlSessionFactory    SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);    //获得SqlSession: 连接数据库    SqlSession session=factory.openSession();     //数据库操作: CURD    //执行数据库操作后,可以用其返回的数据类型接收结果    类型 对象名 = session.CURD方法名("命名空间.业务标识名");//映射文件中的命名空间和业务标识名    //执行映射文件中的哪个SQL     //提交事务    session.commit();    //关闭连接    session.close();    //关闭流    is.close();

Remarks: CURD refers to the operations in the database: create (Create), update (Update), read (Retrieve), delete (Delete) ​​​​

1.5 Examples

1.5.1 mybatis-config.xml configuration file

<?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="development">        <environment id="development">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver"/>                <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>                <property name="username" value="root"/>                <property name="password" value="123456"/>            </dataSource>        </environment>    </environments>    <!--添加映射文件-->    <mappers>        <mapper resource="bean/UserMapper.xml"/>    </mappers></configuration>

1.5.2 UserMapper.xml mapping file for user table operations

<?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"><!--在当前XML中编写针对User的CURD操作命令--><mapper namespace="my.mybatis">    <select id="listUser" resultType="bean.User">        select * from user    </select>     <insert id="addUser" parameterType="bean.User" >        insert into user(name,sex,age,address) values(#{name},#{sex},#{age},#{address})    </insert></mapper>

1.5.3 user entity class

package bean; public class User {    private int id;    private String name;    private char sex;    private int age;    private String address;     public User() {    }     public User(int id, String name, char sex, int age, String address) {        this.id = id;        this.name = name;        this.sex = sex;        this.age = age;        this.address = address;    }     @Override    public String toString() {        return "\nUser{" +                "id=" + id +                ", name='" + name + '\'' +                ", sex=" + sex +                ", age=" + age +                ", address='" + address + '\'' +                '}';    }     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 char getSex() {        return sex;    }     public void setSex(char sex) {        this.sex = sex;    }     public int getAge() {        return age;    }     public void setAge(int age) {        this.age = age;    }     public String getAddress() {        return address;    }     public void setAddress(String address) {        this.address = address;    }}

1.5.4 main method test

package test;  import bean.User;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 TestMyBatis {    public static void main(String[] args) throws IOException {        //获得MyBatis的配置文件: 数据库信息,映射文件信息[SQL]        InputStream is=Resources.getResourceAsStream("mybatis-config.xml");//参数为配置文件的位置: a/mybatis-config.xml        //基于配置信息创建SqlSessionFactory        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);        //获得SqlSession: 连接数据库        SqlSession session=factory.openSession();         //数据库操作: CURD        List<User> list=session.selectList("my.mybatis.listUser");        System.out.println(list);         //提交事务        session.commit();        //关闭连接        session.close();    }}

2. Understanding the configuration file

2.1 Recognize the configuration file:

Introduction

The configuration file of MyBatis contains information that affects the behavior and properties of MyBatis, and controls the overall operation of MyBatis. The configuration file mainly configures the data source [driver class, URL, account number, password], transaction management, and loads the specified mapping file.

Description:

1. Customize the name and location of the MyBatis configuration file.

2. MyBatis does not provide source code and cases, please refer to the official website or user guide for configuration and mapping content

3. The top-level structure of the MyBatis configuration file is as follows:

Basic format:

You can also go to the official website: https://mybatis.org/mybatis-3/zh/getting-started.html or view the PDF in the downloaded frame compression package

2.2 Configuration label:

<environments>:

effect:

Declare a set of operating environment. [Support multiple databases]

Attributes:

default: Set the default operating environment, the attribute value is the id value of a certain <environment>.

<environment>:

effect:

Define 1 operating environment

Attributes:

id: Set the anonymous name of the current environment, the name is arbitrary. Usually development and work.

<transactionManager>:

effect:

Specify the transaction manager, MyBatis contains 2 types of transaction managers [JDBC and MANAGED]

Attributes:

type: JDBC[Use JDBC commit and rollback settings],MANAGED[Use other containers to manage transaction commit and rollback]

<dataSource>:

effect:

This tag configures the resources of the JDBC connection object through the standard JDBC data source interface

Attributes:

type: Set the type of the data source, the attribute value is POOLED|UNPOOLED|JNDI

POOLED: Use connection pool. Remove the connection from the connection pool, and put the connection back to the connection pool when it is closed

UNPOOLED: Do not use connection pool. A new connection is opened every time, and the connection will be completely closed when it is closed

JNDI: Get connections from other containers

<property>:

effect:

Define the specified attributes and values ​​of the data source

Attributes:

name: attribute name. In <dataSource>, name is usually driver/url/username/password or other

value: attribute value.

2.3 Configure data source:

Method 1: Write the parameter value directly in the property

<dataSource type="POOLED">    <property name="driver" value="com.mysql.jdbc.Driver"/>    <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>    <property name="username" value="root"/>    <property name="password" value="123456"/></dataSource>

Method 2: Declare outside, call inside

<!--配置环境--><properties>    <property name="mydriver" value="com.mysql.jdbc.Driver"/>    <property name="myurl" value="jdbc:mysql://localhost:3306/mydb"/>    <property name="myusername" value="root"/>    <property name="mypassword" value="123456"/></properties><environments default="development">    <environment id="development">        <transactionManager type="JDBC"/><!--配置事务管理的方式: JDBC,MANAGED-->        <!--配置数据源: 账户/密码  URL  驱动器  连接数据库 -->        <dataSource type="POOLED"><!--type定义数据连接方式: POOLED[使用连接池]|UNPOOLED|JNDI-->            <property name="driver" value="${mydriver}"/><!--Class.forName("com.mysql.jdbc.Driver")-->            <property name="url" value="${myurl}"/>            <property name="username" value="${myusername}"/>            <property name="password" value="${mypassword}"/>        </dataSource>    </environment></environments>

Method 3: Read the properties configuration file

<properties resource="DBSource.properties" /><environments default="development">    <environment id="development">        <transactionManager type="JDBC"/><!--配置事务管理的方式: JDBC,MANAGED-->        <dataSource type="POOLED"><!--type定义数据连接方式: POOLED[使用连接池]|UNPOOLED|JNDI-->            <property name="driver" value="${db.driver}"/><!--Class.forName("com.mysql.jdbc.Driver")-->            <property name="url" value="${db.url}"/>            <property name="username" value="${db.user}"/>            <property name="password" value="${db.password}"/>        </dataSource>    </environment></environments>

DBSource.properties file:

# 键名=值  键名自定义db.driver=com.mysql.jdbc.Driverdb.url=jdbc:mysql://localhost:3306/mydbdb.user=rootdb.password=123456

Way 4: understand

2.4 Load the mapping file:

Way 1:  <mappers>

<mappers>:    格式:    <mapper resource/url/class="映射文件路径"></mappers>

Description:

1.resource: Use the relative class path to indicate the location of the mapping file. For example, bean/User.xml

2.url: Use an absolute path to indicate the location of the mapping file. For example: file:///bean/User.xml

3.class: Use the full name of the class to indicate the location of the mapper interface. For example: bean.UserMapper[UserMapper is the interface

Method 2: <package>

format:

<package name="package name" />

Description:

All interface classes in the specified package will be registered in MyBatis.

Note: The name of the mapper interface and the mapping file must be the same, and in the same directory

|----Custom alias:

format:

<typeAliases>

<!-- Method 1: Define the alias of the specified class -->

<typeAlias ​​type="class full name" alias="alias [name arbitrary]" />

<!-- Method 2: Define aliases in batches -->

<package name="package name" />

</typeAliases>

Description:

The name value is the package name, and the alias of the class in the package is the class name [uppercase and lowercase]

3. Mapping files

|----Recognize the mapping file:
Introduction:
    The mapping file of MyBatis is mainly used to define business operation commands, realize the mapping of objects and data table fields, and control the encapsulation of the final result. MyBatis is built for SQL and has relatively the same functions JDBC code, reducing the amount of code by 95%.
Description:
    1. The name and location of the mapping file are arbitrary, and it is not required to be in the same location as the POJO class.
    2. MyBatis does not provide source code and cases. For configuration and mapping content, refer to the official website or user guide
    3. The top-level structure of the .MyBatis mapping file is as follows:
    omit, take a screenshot by yourself

Basic format:
<mapper namespace="anonymous space">
    <select/insert/update/delete, etc. id="business identification name" resultType="the object of the package result [entity class full name]" parameterType="placeholder Source">
        SQL commands
    </select/insert/update/delete, etc.>
</mapper>

Description:
    1.namespace: Represents a namespace, similar to the role of a Java package. [Optional in the old version, must be configured in the new version]
    2.id: Set anonymity for business operations, easy to call in the program.
    3.parameterType: Point out that it will be passed The type of the placeholder in the SQL command can be a normal type or a custom type.
    4.resultType: indicates the type of the result of the SQL command execution. If the result is a set, the attribute value is the type name of the element.
    5.statementType: Set the type of SQL execution object: STATEMENT, PREPARED[default value], CALLABLE.
    6. The semicolon after the end      of the SQL command, optional
|-----placeholder:
Introduction:
SQL commands in the Mybatis mapping file, support Set the value of the field as a placeholder. Like JDBC, you need to indicate the value of the placeholder when you execute the SQL command.
Format:
    #{Placeholder name}
Description:
1. The value of the placeholder can come from the entity object ,Map collection, ordinary data
2. If the value of the placeholder comes from ordinary data, the placeholder name is arbitrary. [Only 1 placeholder, such as id]
3. If the value of the placeholder comes from the entity object, the placeholder The name must be the attribute name of the object
4. If the value of the placeholder is from the Map collection, the placeholder name must be the key name

|-----Result mapping
Introduction:
    MyBatis automatically maps the attributes of the POJO object with the field names in the query result set or the placeholder names in the add/modify/delete to realize the mapping relationship between the object and the table.
    At the same time, MyBatis provides manual Set POJO object attributes and execution results mapping method: <resultMap>.

Solve that the field name is different from the attribute name and cannot be mapped:
Method 1: Set the field anonymous
 select id, username as name, sex, age, address from user
Method 2: <resultMap>
    <select id="" resultType="" resultMap=" resultMap Anonymous A">
        SQL command
    </select>
    <!--Custom mapping rules-->
    <resultMap id="resultMap Anonymous A" type="full name of the entity class">
        <id property="primary key attribute" column= "Primary key field name" />
        <result property="common attribute" column="field name" />
    </resultMap>

4. CURD operation [Getting started]

5. Tools CURD

6. Based on Mapper interface CURD

7. Concatenation

7.1 Placeholder:

When the value of the placeholder is inserted into SQL, it will automatically wrap the content in single quotes.

Format: #{splicing symbol name}

7.2 Concatenation:

When the value responsible for splicing is inserted into SQL, it is only used as a splicing of commands and no other processing is performed.

Format: ${splicing symbol name}

Requirements:
     1. The source of the value of the splicing symbol can be ordinary data, entity object, Map collection
    2. If the value of the splicing symbol comes from ordinary data, the name of the splicing symbol must be value
    3. If the value of the splicing symbol comes from the entity object, splicing The name of the symbol must be the attribute name [provide setter]
    4. If the value of the splicing symbol comes from the Map collection, the name of the splicing symbol must be the key name.

Summary: When using fuzzy queries, you need to pay attention to the splicing% when using placeholders, and you do not need to use splicing characters, but the splicing characters are easy to be injected by SQL