The first Mybatis program

1. What is Mybatis?

1. MyBatis is an excellent persistence layer framework
2. MyBatis avoids almost all JDBC code and manual setting of parameters and obtaining result sets .
3. MyBatis can use simple XML or annotations to configure and map primitive types, interfaces and Java POJOs (Plain Old Java Objects) as records in the database.

2. How to get Mybatis?

maven warehouse:

<!-- -->

3. What is the persistence of Mybatis, and why do I need Mybatis?

Persistence is the process of transforming the data of the program between the persistent state and the transient state.
1. Help the program save the data in the database.
2. Convenience
3. The traditional JDBC code is too complicated, simplified, framed, and automated.

4. The first Mybatis program

Idea: Build an environment—import Mybatis—write code—test
1. Build a database


USE `mybatis`;


INSERT INTO `user`(`id`,`name`,`pwd`) VALUES 

2. Create a new project

  • Create a new ordinary maven project
  • Delete the src directory
  • Import maven dependencies

3. Create a new module and
write the core configuration file of Mybatis

Insert picture description here
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-// Config 3.0//EN"
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
        <mapper resource="com/xiong/dao/UserMapper.xml"/>

Don't forget to write this mapper mapping file

Insert picture description here

4. Write the tool class of Mybatis

//sqlSessionFactory --> sqlSession
package com.xiong.utils;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {

        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
    //既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。
    // SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();

5. Write database entity class code,
this is easy to write

package com.xiong.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {

    public User(int id, String name, String pwd) { = id; = name;
        this.pwd = pwd;

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getPwd() {
        return pwd;

    public void setPwd(String pwd) {
        this.pwd = pwd;

    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +

6. Write Dao layer interface

package com.xiong.dao;
import com.xiong.pojo.User;
import java.util.List;
public interface UserDao {
    List<User> getUser();

7. The interface implementation class is changed from the original UserDaoImpl to a Mapper configuration file.
Here is an explanation. It is better to change the encoding to GBK. Many problems were encountered in the test.

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<mapper namespace="com.xiong.dao.UserDao">
    <select id="getUser" resultType="com.xiong.pojo.User">
        select * from mybatis.user;

8. Test
Create the test code under the test package as in the original directory

Insert picture description here
package com.xiong.dao;

import com.xiong.pojo.User;
import com.xiong.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UseDaoTest {
    public void test(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> user = mapper.getUser();
        for (User user1 : user) {


5. Problems encountered

  • The configuration file is not registered
  • Binding interface error

1. The solution to the org.apache.ibatis.exceptions.PersistenceException error report when I first
learned mybatis Add the following build to the pop.xml file, because the resources will not be found when it is generated

        <!-- 定义classpath -->
            <!-- resources文件 -->
                <!-- 是否被过滤,如果被过滤则无法使用 -->
            <!-- java文件夹 -->
                <!-- 引入映射文件等 -->

2. Pay attention to the following points
1. In mapper.xml, namespace is equal to the mapper interface address

Insert picture description here

2. The method name in the interface is consistent with the id of the statement in mapper.xml

Insert picture description here

3. The input parameter type of the method in the interface is consistent with the type specified by the parameterType of the statement in mapper.xml.

Insert picture description here

4. The return value type of the method in the interface is consistent with the type specified by the resultType of the statement in mapper.xml.

Test result:

Insert picture description here

Compared with JDBC connection database query, higher school, no need to write redundant code, only need to change the sql statement, but the bottom layer is still JDBC connection database