mybatis from scratch

Step 1: Build an experimental database

CREATE DATABASE `mybatis`;

USE `mybatis`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(2,'张三','abcdef'),(3,'李四','987654');

IDEA link database
import jar package dependency

<dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>8.0.12</version>
       </dependency>
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.5.4</version>
       </dependency>

Test environment dependency

<dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>4.12</version>
       </dependency>

Step 3: Preparation

According to mybatis official document

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

We built a tool class

com.kuang.utils.MybatisUtils

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    //使用Mybatis第一步,获取sqlSessionFactory对象
    static{
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream;
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getsqlsession(){
        SqlSession sqlSession=sqlSessionFactory.openSession();
        return sqlSession;
    }
}

Resource requires the core configuration file resource = "mybatis-config.xml"
src/main/resources/mybatis-config.xml

<?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配置文件-->
<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?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册!-->
<mappers>
    <mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
</configuration>

End of preparation

The fourth step entity class

com.kuang.pojo.User

package com.kuang.pojo;
//实体类
public class User {
    private int id;
    private String name1;
    private String psd;

    public User() {
    }

    public User(int id, String name1, String psd) {
        this.id = id;
        this.name1 = name1;
        this.psd = psd;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName1() {
        return name1;
    }

    public void setName1(String name1) {
    sibu    this.name1 = name1;
    }

    public String getPsd() {
        return psd;
    }

    public void setPsd(String psd) {
        this.psd = psd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name1='" + name1 + '\'' +
                ", psd='" + psd + '\'' +
                '}';
    }
}

The fifth step is to write the interface (this is more important, you need to write the method here for the addition, deletion, and modification of the database)

com.kuang.dao.UserMapper

public interface UserMapper {
    //查询全部用户
    List<User> getUserList();
    //根据ID查询用户
    User getUserById(int id);
    //insert一个用户
    int addUser(User user);
    //修改用户
    int updataUser(User user);
    //删除操作
    int deleteUser(int id);
}

The usrMapper.xml file replaces the original implementation class (namespace binding interface location, inside tag id binding method, return value type: resultType)

com/kuang/dao/UserMapper.xml

<?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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.kuang.dao.UserMapper">
    <select id="getUserList" resultType="com.kuang.pojo.User">
    select * from user
    </select>
    <select id="getUserById" resultType="com.kuang.pojo.User">
        select name1 from user where id='1'
    </select>
    <insert id="addUser" parameterType="com.kuang.pojo.User">
        insert into mybatis.user(id,name1,psd)values(#{id},#{name1},#{psd});
    </insert>
    <update id="updataUser" parameterType="com.kuang.pojo.User">
        update mybatis.user set name1=#{name1},psd=#{psd} where id=#{id};
    </update>
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id =#{id};
    </delete>
</mapper>

Note that UserMapper.xml here needs to be registered in Mappers in the core configuration file

Annotation (implemented through reflection)

The role of annotations is equivalent to the realization of the xml configuration file function. We can remove the UserMapper.xml file and add annotations directly to the interface.

public interface UserMapper {
    @Select("select * from user")
    List<User> getUsers();
}

Of course, we also make corresponding changes in the configuration file and bind it to the interface

<mappers>
    <mapper class="com.kuang.dao.UserMapper"/>
</mappers>

In other words, there are two ways to implement the interface, one is annotation, the other is using .xml files.

Using annotations to map simple statements will make the code more concise, but for slightly more complex statements, Java annotations are not enough and appear more confusing. Therefore, if you need to accomplish very complex things, it is best to use XML to map statements.

Seventh step test

public class UserDaoTest {
    @Test
    public void test(){
        //第一步,获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getsqlsession();
        //执行sql
        UserMapper userDao = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userDao.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        //关闭sqlSession
        sqlSession.close();
    }
    @Test
    public void test1(){
        SqlSession sqlSession1 = MybatisUtils.getsqlsession();
        UserMapper mapper = sqlSession1.getMapper(UserMapper.class);
        User userById = mapper.getUserById('1');
        System.out.println(userById);
        sqlSession1.close();
    }
    //增删改需要提交事务
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getsqlsession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.addUser(new User(4,"哈哈","123123"));
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getsqlsession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updataUser(new User(4,"呵呵","123123"));
        sqlSession.commit();

        sqlSession.close();
    }
    @Test
    public void deleteUser(){
        SqlSession sqlsession = MybatisUtils.getsqlsession();
        UserMapper mapper = sqlsession.getMapper(UserMapper.class);
        mapper.deleteUser(4);
        sqlsession.commit();
        sqlsession.close();
    }


}

Mybatis execution process

Insert picture description here