Brief introduction and use of Mybatis of SSM

Posted by ridgedale on Tue, 04 Jan 2022 04:30:42 +0100

introduce

MyBatis was originally an open source project ibatis of apache. In 2010, the project was migrated from apache software foundation to google code and renamed MyBatis. Moved to Github in November 2013.

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

Compared with JDBC

  1. Through parameter mapping, Mybatis can flexibly configure parameters in the configuration file in SQL statements to avoid configuring parameters (JDBC) in Java classes
  2. Through the output mapping mechanism, Mybatis automatically maps the retrieval of the result set into corresponding Java objects to avoid manual retrieval of the result set (JDBC)
  3. Mybatis can manage database connections through Xml configuration files.

Overall architecture and operation process of MyBatis

The overall structure of Mybatis is composed of data source configuration file, Sql mapping file, session factory, session, executor and underlying encapsulation object.

Data source profile

The configuration information of the database is separated from the application by configuration, which is managed and configured by an independent module. The data source configuration file of Mybatis includes database driver, database connection address, user name and password, transaction management, etc. it can also configure the number of connections and idle time of the connection pool.
A sqlmapconfig The basic configuration information of XML is as follows:

<configuration>
    <!-- Load database properties file -->
    <properties resource="db.properties"></properties>
    <environments default="development">
        <environment id="development">
            <!--use JDBC practical management -->
            <transactionManager type="JDBC"></transactionManager>
            <!--Connection pool -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
</configuration>

Sql mapping file

All database operations in Mybatis will be based on the mapping file and the configured sql statements (or use annotations to write sql statements in the dao layer interface). Any type of sql statements can be configured in this configuration file. The framework will complete the mapping configuration of sql statements and input and output parameters according to the parameter configuration in the configuration file.
Mapper. The XML configuration file is roughly as follows:

<!DOCTYPE mapper 
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sl.dao.ProductDao">
    <!-- according to id query product surface
        resultType:Return value type. A database record corresponds to an object of entity class
        parameterType:Parameter type, that is, the type of query criteria
     -->
    <select id="selectProductById" resultType="com.sl.po.Product" parameterType="int">
     <!-- Here and ordinary sql The query statement is almost the same. For only one parameter, the following #{id} represents a placeholder. You don't have to write id in it. You can write anything, but don't leave it empty. If there are multiple parameters, you must write the attribute -- > in the pojo class
        select * from products where id = #{id}
    </select>
</mapper>

Session factory and session

The SqlSessionFactory class of the session factory in Mybatis can load the resource file to read the data source configuration sqlmapconfig XML information to generate a session instance SqlSession that can interact with the database. The session instance SqlSession is based on mapper The sql configured in the XML file operates on the database.

Operation process

The session factory SqlSessionFactory obtains sqlmapconfig by loading the resource file XML configuration file information, and then generate a session instance SqlSession that can interact with the database. The session instance can perform corresponding addition, deletion, modification and query operations according to the SQL configuration in the Mapper configuration file. Within the SqlSession session instance, the database is operated through the Executor, which relies on the encapsulated object Mappered Statement, which is sub packaged from Mapper The information read from the XML file (SQL statement, parameters, result set type). Mybatis realizes the interaction with the database through the combination of the Executor and Mappered Statement.
Execution flow chart:

Simple use

Take maven project as an example.

Dependent pom file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sl</groupId>
    <artifactId>mybatis-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <junit.version>4.12</junit.version>
        <mybatis.version>3.4.1</mybatis.version>
        <mysql.version>5.1.32</mysql.version>
        <log4j.version>1.2.17</log4j.version>
    </properties>
    <dependencies>
        <!-- unit testing  -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <!-- <scope>test</scope> -->
        </dependency>
        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!-- Log processing -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
    </dependencies>
</project>

Data source configuration file 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">
<configuration>
<!-- Load profile -->
    <properties resource="db.properties"></properties>
    <environments default="development">
        <!-- id Property must be the same as above defaut agreement -->
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <!--dataSource Elements use standard JDBC Data source interface JDBC Connect object source -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
     <!—Affirms mapper file -->
        <mappers>
        <!-- xml Implement registration productMapper.xml file -->
        <mapper resource="mapper/productMapper.xml"></mapper>
    </mappers>
</configuration>

SQL mapping configuration file productmapper 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="com.sl.mapper.ProductMapper">
    
    <select id="selectAllProduct" resultType="com.sl.po.Product">
        select * from products
    </select>
    
</mapper>

Test code testclient java

//Using productmapper XML configuration file
public class TestClient {

    //Define session SqlSession
    SqlSession session =null;
    
    @Before
    public void init() throws IOException {
        //Define mabatis global profile
        String resource = "SqlMapConfig.xml";
        
        //Load mybatis global configuration file
        //InputStream inputStream = TestClient.class.getClassLoader().getResourceAsStream(resource);
        
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(inputStream);
        //Generate a session based on sqlsession factory
        session = factory.openSession();    
    }

    
    //Query all data of all user tables
    @Test
    public void testSelectAllUser() {
        String statement = "com.sl.mapper.ProductMapper.selectAllProduct";
        List<Product> listProduct =session.selectList(statement);
        for(Product product:listProduct)
        {
            System.out.println(product);
        }
        //Close session
        session.close();    
    }
}

Data corresponding entity class

public class Product {
    private int Id;
    private String Name;
    private String Description;
    private BigDecimal UnitPrice;
    private String ImageUrl;
    private Boolean IsNew;

    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 String getDescription() {
        return Description;
    }

    public void setDescription(String description) {
        this.Description = description;
    }

    public BigDecimal getUnitPrice() {
        return UnitPrice;
    }

    public void setUnitPrice(BigDecimal unitprice) {
        this.UnitPrice = unitprice;
    }

    public String getImageUrl() {
        return Name;
    }

    public void setImageUrl(String imageurl) {
        this.ImageUrl = imageurl;
    }

    public boolean getIsNew() {
        return IsNew;
    }

    public void setIsNew(boolean isnew) {
        this.IsNew = isnew;
    }

    @Override
    public String toString() {
        return "Product [id=" + Id + ", Name=" + Name + ", Description=" + Description
                + ", UnitPrice=" + UnitPrice + ", ImageUrl=" + ImageUrl + ", IsNew=" + IsNew+ "]";
    }
}

Topics: Java