Mybatis learning record (I)

Time:2021-11-24

1、 Mybatis HelloWorld

1. Create a project using Maven. The project directory is as follows

Mybatis learning record (I)

2. Introduce dependency in Maven’s pom.xml

It mainly includes the dependencies of mybatis, MySQL and JUnit, and then it can be developed.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>test03</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

3. Write the mybatis configuration file mybatis-config.xml file

It is mainly used to configure data sources and related mappers*. XML file

<?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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

4. Create user table and write user class

Mybatis learning record (I)

package com.jt;

public class User {
    private int id;
    private String username;
    private String password;

    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 String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

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

5. Write usermapper class

package com.jt;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Map;

public interface  UserMapper {
   public User selectUser(int id);
   public User  selectUserByIdAndName(@Param("id") Integer id,@Param("username") String username);
   public User  selectUserByIdAndNameUseMap(Map map);

   public Integer insertUser(User user);
   public boolean updateUser(User user);
   public Integer deleteUserById(int id);
}

6. Write the usermapper.xml 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.jt.UserMapper">
    <select id="selectUser" resultType="com.jt.User">
        select * from test01 where id = #{id}
    </select>
    <select id="selectUserByIdAndName" resultType="com.jt.User">
        select * from test01 where id = #{id} and username=#{username}
    </select>
    <select id="selectUserByIdAndNameUseMap" resultType="com.jt.User">
        select * from test01 where id = #{id} and username=#{username}
    </select>
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        insert into test01 (username,password) values(#{username},#{password})
    </insert>
    <update id="updateUser" parameterType="com.jt.User">
        update test01 set username=#{username} where id=#{id}
    </update>
    <delete id="deleteUserById">
        delete from test01 where id=#{id}
    </delete>
</mapper>

7. Write test class

import com.jt.User;
import com.jt.UserMapper;
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.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;

public class HelloTest {
    @Test
    public void selectTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            User user = userMapper.selectUser(1);
            System.out.println(user);
        }finally {
            sqlSessionFactory.openSession();
        }

    }
    @Test
    public void selectByIdAndNameTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            User user = userMapper.selectUserByIdAndName(5,"3");
            System.out.println(user);
        }finally {
            sqlSessionFactory.openSession();
        }

    }
    @Test
    public void selectByIdAndNameUseMapTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            Map map = new LinkedHashMap();
            map.put("id",5);
            map.put("username","3");

            User user = userMapper.selectUserByIdAndNameUseMap(map);
            System.out.println(user);
        }finally {
            sqlSessionFactory.openSession();
        }

    }

    @Test
    public void insertTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            User user01 = new User();
            user01.setUsername("4");
            user01.setPassword("4");
            userMapper.insertUser(user01);
            System.out.println(user01.getId());

        }finally {
            sqlSessionFactory.openSession();
        }
    }
    @Test
    public void updateTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            User user01 = new User();
            user01.setId(2);
            User01.setusername ("modification 1");

            boolean res = userMapper.updateUser(user01);
            System.out.println(res);

        }finally {
            sqlSessionFactory.openSession();
        }
    }
    @Test
    public void deleteTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);


           int res =  userMapper.deleteUserById(1);
            System.out.println(res);

        }finally {
            sqlSessionFactory.openSession();
        }
    }
}