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:

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>

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

CREATE DATABASE `mybatis`;

USE `mybatis`;

CREATE TABLE `user`(
  `id` INT(20) NOT NULL PRIMARY KEY,
  `name` VARCHAR(30) DEFAULT NULL,
  `pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user`(`id`,`name`,`pwd`) VALUES 
(1,'狂神','123456'),
(2,'张三','123456'),
(3,'李四','123890')

2. Create a new project

  • Create a new ordinary maven project
  • Delete the src directory
  • Import maven dependencies
<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.2</version>
        </dependency>
    </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 "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <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"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/xiong/dao/UserMapper.xml"/>
    </mappers>
</configuration>

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.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {

        try {
            //使用Mybatis第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //创建一个能执行sql的对象
    //既然有了 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) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    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 getPwd() {
        return pwd;
    }

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

    @Override
    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 "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xiong.dao.UserDao">
    <select id="getUser" resultType="com.xiong.pojo.User">
        select * from mybatis.user;
    </select>
</mapper>

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 {
    @Test
    public void test(){
        //获得sqlsession对象
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        System.out.println(sqlSession);
        //执行sql
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> user = mapper.getUser();
        for (User user1 : user) {
            System.out.println(user1);
        }
        sqlSession.close();
    }

}

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

 <build>
        <!-- 定义classpath -->
        <resources>
            <!-- resources文件 -->
            <resource>
                <directory>src/main/resources</directory>
                <!-- 是否被过滤,如果被过滤则无法使用 -->
                <filtering>false</filtering>
            </resource>
            <!-- java文件夹 -->
            <resource>
                <directory>src/main/java</directory>
                <!-- 引入映射文件等 -->
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

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 mapper.java 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 mapper.java 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 mapper.java 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