Detailed explanation of Mybatis components

1. MyBatis core components

The core components of MyBatis are divided into 4 parts:

  1. SqlSessionFactoryBuilder: Generate SqlsessionFactory according to configuration or code, and use distributed build Builder mode (builder mode).

  2. SqlSessionFactory: Factory interface, relying on it to generate SqlSession, using factory mode.

  3. SqlSession: Session, you can either send sql statement or get the interface of mapper mapping file.

  4. Sql Mapper: Mapper, which is composed of mapper xml file and a corresponding java interface. It needs to give the corresponding sql and mapping rules. It is responsible for sending sql and executing it, and returning the result.
    Insert picture description here

2、SqlSessionFactory

  The construction of SqlSessionFactory needs to be generated step by step with the help of SqlSessionFactoryBuilder. The most commonly used method is to read the configuration file XML by SqlSessionFactoryBuilder to generate SqlSessionFactory , but Mybatis also provides a Java code configuration method (not recommended, the code is lengthy).
  When the configuration file is provided, Mybatis will construct the entire Mybatis context through the Configuration class object. (SqlSessionFactory is an interface, there is SqlSessionManager (used in multi-threaded environment) and DefaultSqlSessionFactory (used in general)). Each Mybatis application is based on an instance of SqlSessionFactory, its sole role is to produce the core interface object SqlSession. So it should be handled in singleton mode.

3、SqlSession

  In Mybatis, SqlSession is the core interface, and its role is similar to the Connection object in JDBC, which represents the start of a database link resource. Its main functions include access to the mapper interface , sending SQL to the database , and transaction control . But SqlSession is like a proxy object, and the one who is responsible for the work is the Executor. It should be noted that SqlSession represents a database connection resource, and it should be shut down in time. Otherwise, when the database link resource is exhausted, the system will be paralyzed.

4、Mapper

  It is the most complex and important component in mybatis. It consists of an interface and corresponding xml file (or annotation). Its main functions include:

  1. Describe mapping rules
  2. Provide sql statement, configuration parameter type, return value type, etc.
  3. Configure cache
  4. Provide dynamic sql function

5. Introduction of life cycle

  1. SqlSessionFactoryBuilder: Its role is to create SqlSessionFactory, so it can only exist in the method of creating SqlSessionFactory, and not let it exist for a long time.
  2. SqlSessionFactory: can be regarded as a database connection pool, occupying the link resources of the database, the essence of mybatis is to operate the database, so he should exist in the entire mybatis application.
  3. SqlSession: Seen as a database connection, it only survives one business request. When a request ends, resources should be returned to SqlSessionFactory.
  4. Mapper: An interface created by SqlSession, representing business processing logic in a request, so the life cycle should be consistent with SqlSession.

6. Simple entry

The main directories are as follows:
Insert picture description here

6.1, pom file

Add dependencies: mainly mybatis and mysql dependency packages (required), unit tests and logs (optional)

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.37</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
</dependencies>

6.2, POJO 类

package domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable{

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

6.3, IUserDao

package dao;

import domain.User;
import java.util.List;

public interface IUserDao {
    /**
     * 查询所有操作
     * @return
     */
    List<User> findAll();
}

6.4 IUserDao.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="dao.IUserDao">
    <!--配置查询所有-->
    <select id="findAll" resultType="domain.User">
        select * from user
    </select>
</mapper>

6.5、SqlMapConfig.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">
<!-- mybatis的主配置文件 -->
<configuration>
    <!-- 配置环境 -->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
    <mappers>
        <mapper resource="dao/IUserDao.xml"/>
    </mappers>
</configuration>

6.6, log files

If you need to add logs, you need a configuration file

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

6.7, Test category

package service;

import dao.IUserDao;
import domain.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 org.junit.Test;

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

/**
 * @author RuiMing Lin
 * @date 2020-04-09 14:49
 */
public class UserService {

    private IUserDao userDao;
    @Test
    //测试方法
    public void Test1() throws Exception{
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        IUserDao userDao = session.getMapper(IUserDao.class);
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user);
        }
        //6.释放资源
        session.close();
        in.close();
    }
}

Please point out any mistakes, welcome to comment or private message exchange! Keep updating Java, Python and big data technology every day, please pay attention!

Published 64 original articles · Like 148 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/Orange_minger/article/details/105453305