In-depth explanation of Mybatis

Introduction    

Mybatis, formerly an open source project of Apache, ibatis, migrated to Google code in 2010 and changed its name to Mybatis.

Migrated to Github in November 2013.

when to use

    If you need a flexible framework that can dynamically generate mappings, Myabtis is indeed the best choice. Compared with Hibernate's full table mapping configuration, it cannot be changed flexibly, it is difficult to assemble complex SQL, and it cannot effectively support stored procedures. Mybatis undoubtedly makes up for the big flaws in this regard. It has dynamic columns, dynamic table names, supports stored procedures, and provides simple caching, log cascading, etc., making it easier to adapt to projects with changing requirements.


Development environment setup:

mybatis Github address: https://github.com/mybatis/mybatis-3

The basic composition of the mybatis framework.

1.SqlMapConfig.xml:

Global configuration file, configure data sources, things, etc., configure the mapping file path (do not master it, it will be managed by spring in future integration)

2.mapper.xml (configure sql statement)

3. SqlSessionFactory (session factory)

Create SqlSession

4. SqlSession session

Operate the database (issue sql add, delete, modify and query)

5.Executor executor (is an interface, there are two implementations of basic executor and cache executor)

Role: SqlSession operates sql through the executor inside

6. Sql Mapper (underlying encapsulation object)

receive an input object,

Store and encapsulate the operation database, including SQL statements, input parameters, and output results.

Output result type.

Below is a simple diagram of them.



Use maven to build our project and add the following configuration to pom.xml.

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

Create a new jdbc.properties file under the resource folder

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
username=root
password=root

Create a new SqlMapConfig.xml under the resource folder

<?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>
    <properties resource="jdbc.properties">
    </properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="sqlmap/userMapper.xml"/>
    </mappers>
</configuration>

Create a new sqlmap folder under the resource folder, and create a new userMapper.xml in it

<?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="test">
    <select id="selectUser" parameterType="int" resultType="com.beyond.mybatis.po.User">
        select * from user WHERE id = #{id}
    </select>
</mapper>

Create a new user table in the database

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  `sex` varchar(255) DEFAULT NULL,
  `addr` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8;

Add a few pieces of test data to it.

Then create a new User class

public class User {
    private int id;
    private String username;
    private Date birthday;
    private String sex;
    private String addr;

    public int getId() {
        return id;
    }

    public void setId(int 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 getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

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

Finally write our first test class

public class MybatisFirst {
    /**
    *   @author:kevin
    * @Description: Query user information based on id
    *   @Date:12:08 2018/3/24
    */
    @Test
    public void findUserById() throws IOException {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //create session factory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //create session
        SqlSession sqlSession = factory.openSession();
        //Operate the database through sqlsession
        User user = sqlSession.selectOne("test.selectUser",1);
        System.out.println(user);
        sqlSession.close();
    }
}

The console prints the user object information, indicating that the construction is successful.




Guess you like

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