MyBatis full version tutorial + source code analysis (1)

1. What is MyBatis

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures and advanced mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native information, and map interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) to records in the database. (From MyBatis official website: http://www.mybatis.org/mybatis-3/zh/index.html)

Let's take a closer look at his introduction

(1) First of all, it is a persistence framework. What is persistence, as the name suggests, is to persist transient data (such as data in memory, which cannot be permanently saved) into persistent data (such as persisting to a database) , can be stored for a long time). The specification defines a mechanism for transforming program data between persistent and transient states. The more popular persistence frameworks are Hibernate and MyBatis.

(2) Its advantage is that it avoids almost all JDBC code and manually setting parameters and obtaining result sets. When we use native JDBC code to implement database addition, deletion, modification and query, we will definitely write a lot of redundant code such as database connection, Map the retrieved data prototypes into objects. Of course, we can manually abstract this class method into a tool class in our own project. But when each project needs this kind of tool class, we can organize it and encapsulate it as a jar package and use it anywhere. The bottom layer of mybatis implements this kind of tool class.

(3) Method: Configure and map native information through XML or annotations, obtain configuration through XML, and invade classes through annotations. This is the usual way of a large number of open source frameworks.

More information can be found on MyBatis official website

2. MyBatis project construction

2.1. Prepare the development environment

(1) Create a new maven project,

(2) The latest version of mybatis is mybatis-3.4.5, and the pom file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<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.vichoufa</groupId>
    <artifactId>mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>


(3) Establish a test database

create database test default character utf8 COLLATE utf8_general_ci;  
CREATE TABLE `dept` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `dept_name` varchar(50) DEFAULT NULL,  
  PRIMARY KEY (`id`)  
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;  
insert into dept (dept_name) values ​​('Development Department'),('Operation Department'),('Sales Department'),('Personnel Department'),('Finance Department'),('General Manager's Office'), ('Logistics Department'),('Marketing Department');  

run in mysql


At this point, the preparatory work for the development environment has been completed.
2.2. Use MyBatis to query the data in the table

(1) Add a 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">
<!-- Put some global configuration in this file such as handler, objectFactory, plugin, and mapping path of mappers-->
<configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC" />
                <!-- Configure database connection information-->
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver" />
                    <property name="url" value="jdbc:mysql://localhost:3306/test" />
                    <property name="username" value="root" />
                    <property name="password" value="root" />
                </dataSource>
            </environment>
        </environments>
</configuration>
(2) Create a new corresponding entity class


code show as below

package com.vichoufa.mybatis.pojo;

/**
 * Created by vichoufa on 2017/11/19 0019.
 */
public class DeptPojo {
    private int id;

    private String name;

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

    @Override
    public String toString() {
        return "DeptPojo{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

(3) Define the sql file that operates the dept table


<?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">
<!-- Specify a unique namespace for this mapper, the value of the namespace is customarily set to the package name + sql mapping file name, so that the value of the namespace can be guaranteed to be unique
 For example, namespace="com.vichoufa.mybatis.mapper.deptMapper" is com.vichoufa.mybatis.mapper(package name)+deptMapper(deptMapper.xml
 file without suffix)
 -->
<mapper namespace="com.vichoufa.mybatis.mapper.deptMapper">
    <!--More ID retrieval department-->
    <select id="selectDeptById" parameterType="int"
            resultType="com.vichoufa.mybatis.pojo.DeptPojo">
        select id, name
        from dept
        where id = #{id}
    </select>
</mapper>

(4) Add the mapping file to the mybatis.xml mapping

<?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">
<!-- Put some global configuration in this file such as handler, objectFactory, plugin, and mapping path of mappers-->
<configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC" />
                <!-- Configure database connection information-->
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver" />
                    <property name="url" value="jdbc:mysql://localhost:3306/test" />
                    <property name="username" value="root" />
                    <property name="password" value="root" />
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="com/vichoufa/mybatis/mapper/deptMapper.xml"></mapper>
        </mappers>
</configuration>

(5) Write test code

package com.vichoufa.mybatis.test;

import com.vichoufa.mybatis.pojo.DeptPojo;
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.IOException;
import java.io.Reader;

/**
 * Created by vizhoufa on 2017/11/19 0019.
 */
public class TestDeptMapper {
    @Test
    public void testSelectDeptById() throws IOException {
        //mybatis configuration file
        String resource = "MyBatis.xml";
        //Use the class loader to load the configuration file of mybatis (it also loads the associated mapping file)
//        InputStream is = TestDeptMapper.class.getClassLoader().getResourceAsStream(resource);
// //Build a factory for sqlSession
//        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        //Use the Resources class provided by MyBatis to load the configuration file of mybatis (it also loads the associated mapping file)
        Reader reader = Resources.getResourceAsReader(resource);
        //Build a factory for sqlSession
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //Create a sqlSession that can execute the sql in the mapping file
        SqlSession session = sessionFactory.openSession();

        String statement = "com.vichoufa.mybatis.mapper.deptMapper.selectDeptById";//Map sql identification string
        //Execute the query to return the sql of a unique user object
        DeptPojo dept = session.selectOne(statement, 1);
        System.out.println(dept);
    }
}

(6) Run the test case:


If you have any questions, please leave a message and I will reply in time

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325640515&siteId=291194637