Configure MyBatis

Chapter 1: Overview of the framework

1. Overview of MyBatis Framework
  1. MyBatis is an excellent Java-based persistence layer framework that encapsulates JDBC internally, so that developers only need to pay attention to SQL statements instead of JDBC code, making development easier.
  2. MyBatis configures various Statement objects to be executed through XML or annotations,
    maps the dynamic parameters of SQL in the Java object and the statement , and finally executes the SQL statement. After executing the SQL, the result is finally returned as a Java object.
  3. The idea of ​​half an ORM is adopted. hibernate complete ORM thinking

Chapter 2: MyBatis's entry program (emphasis)

1. Create a database and table structure

create database mybatis_demo;
use mybatis_demo;
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` datetime default NULL COMMENT '生日',
`sex` char(1) default NULL COMMENT '性别',
`address` varchar(256) default NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'老王','2018-02-27
17:47:08','男','北京'),(2,'熊大','2018-03-02 15:09:37','女','上海'),(3,'熊二','2018-03-04
11:34:34','女','深圳'),(4,'光头强','2018-03-04 12:04:06','男','广州');

2. Steps for getting started with MyBatis

1. Create a maven project, just create a Java project.
2. Introduce coordinates
1. Introduce the coordinates of version 3.4.5 of MyBatis
2. Introduce the MySQL-driven jar package, version 5.1.6
3. Introduce the jar package for Junit unit testing
4. Introduce the jar package of log4j, version 1.2.12 (Need to import log4j.properties configuration file)

<dependencies>
<!--mybatis核心包--> 
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>

3. Write the entity class of User, and use the packaging type as much as possible for the attributes. The specific code is as follows
(shortcut key alt+enter: import class; alt+insert: add Getter, Setter, and toString methods)

package com.qcby.entity;
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 + '\'' +
                '}';
    }
}

4. Write UserDao's interface and method

package com.qcby.dao;

import com.qcby.entity.User;

import java.util.List;

/**
 * 查询所有用户
 */
public interface UserDao {
    public List<User> findAll();
}

5. In the resources directory, create a mapper folder. Write the configuration file of UserDao.xml and import the constraint file.

<?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.qcby.dao.UserDao">
    <select id="findAll" resultType="com.qcby.entity.User">
        select * from user
    </select>
</mapper>
  1. mapper namespace="com.qcby.dao.UserDao", called the name space, indicates
    the method to find the findAll in the UserDao interface in the future .
  2. The name of the method in the UserDao interface written by the id attribute in select id="findAll" is fixed.
  3. resultType="com.qcby.entity.User" indicates the return value type of the findAll method.

6. Write the main configuration file, create the SqlMapConfig.xml configuration file (in fact, the name can be any) in the resources directory, import the corresponding constraints, and write the main configuration file. (Shortcut key ctrl+shift+/: quick comment)

<?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>
    <environments default="mysql">
        <environment id="mysql">
            <!--配置事务的类型,使用本地事务策略-->
            <transactionManager type="JDBC"></transactionManager>
            <!--是否使用连接池 POOLED表示使用链接池,UNPOOLED表示不使用连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo"/>
                <property name="username" value="root"/>
                <property name="password" value="2020"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/UserDao.xml"></mapper>
    </mappers>
</configuration>

7. Write the entry program (focus on the steps to get started)

import com.qcby.Dao.UserDao;
import com.qcby.entity.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.After;
import org.junit.Before;
import org.junit.Test;

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

public class UserTest {

    private InputStream in = null;
    private SqlSession session = null;
    private UserDao mapper = null;

    @Before
    public void init() throws IOException {
        //加载主配置文件,目的是为了构建SqlSessionFactory对象
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //通过SqlSessionFactory工厂对象创建SqlSesssion对象
        session = factory.openSession();
        //通过Session创建UserDao接口代理对象
        mapper = session.getMapper(UserDao.class);
    }

    @After
    public void destory() throws IOException {
        //释放资源
        session.close();
        in.close();
    }

    /**
     * 测试查询所有的方法
     */
    @Test
    public void findAll() throws IOException {
         List<User> users = mapper.findAll();
        for (User user:users) {
            System.out.println(user.toString());
        }
    }

}

3. Summary of MyBatis entry process

Insert picture description here