Mybatis component detailed explanation and entry demo

1. MyBatis core components

The core components of MyBatis are divided into 4 parts:

  1. SqlSessionFactoryBuilder: Generate SqlsessionFactory based on 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 send SQL statements, you can also get the interface of the mapper mapping file.

  4. Sql Mapper: The mapper consists of a mapper xml file and a corresponding java interface. The corresponding sql and mapping rules need to be given. It is responsible for sending and executing the sql, and returning the result.
    Insert picture description here

2、SqlSessionFactory

  The construction of SqlSessionFactory needs to be guided 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, code lengthy).
  When the configuration file is provided, Mybatis will construct the entire Mybatis context through the Configuration class object. (SqlSessionFactory is an interface, there are SqlSessionManager (used in a multi-threaded environment) and DefaultSqlSessionFactory (used in general)). Each Mybatis application is based on an instance of SqlSessionFactory as the center, and its only 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. Its function is similar to the Connection object in JDBC, which represents the start of a database link resource. Its main functions include obtaining the mapper interface , sending SQL to the database , and transaction control . But SqlSession is like a proxy object, where Executor is really responsible for the work. It should be noted that SqlSession represents a database connection resource, it must be closed in time, otherwise the system will be paralyzed when the database connection resource is exhausted.

4、Mapper

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

  1. Describe the mapping rules
  2. Provide SQL statements, configuration parameter types, return value types, etc.
  3. Configure cache
  4. Provide dynamic sql function

5. Introduction to life cycle

  1. SqlSessionFactoryBuilder: Its role is to create a SqlSessionFactory, so it can only exist in the method of creating a SqlSessionFactory and not let it exist for a long time.
  2. SqlSessionFactory: It can be regarded as a database connection pool, which occupies the link resources of the database. The essence of mybatis is to operate the database, so it should exist in the entire mybatis application.
  3. SqlSession: It is regarded as a database connection, which only survives a business request. When a request ends, the resources should be returned to SqlSessionFactory.
  4. Mapper: An interface created by SqlSession, representing the 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 dependency: mainly mybatis and mysql dependency package (required), unit test and log (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 class

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 file

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 class

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();
    }
}

Guess you like

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