Mybatis foundation + addition, deletion, modification and query (code example)

First, what is MyBatis?

MyBatis is a state-of-the-art persistence framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all JDBC code and manually setting parameters and retrieving results. MyBatis can use simple XML or Annotations to configure and map primitives, mapping interfaces, and Java POJO s (ordinary old Java objects) to database records.

MyBatis Chinese documents (learning resources):

mybatis – MyBatis 3 | Introduction

MyBatis basic framework construction source code:

https://gitee.com/aaron1996/mybatis

Detailed explanation of MyBatis basic framework:

Basic structure of the project:

 

Project dependencies:

<?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">
    <parent>
        <artifactId>RocketDemo</artifactId>
        <groupId>org.cainiao</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>demo-mybatisJDBC</artifactId>

    <dependencies>
        <!--    springboot Project launcher    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!--    spring Project test dependency    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
            <scope>provided</scope>
        </dependency>
        <!--    mybatis    -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

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

        <!--    mysql    -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <!-- Optional: log4j log setting -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

    <!--  Prevent resource filtering problems  -->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

Note: parent POM The XML file also contains:

 

Database configuration file (dp.properties):

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=root123456

Log configuration file (log4j.properties):

# The following log configuration file can be used in any project and belongs to code that can be written to death

# Output the log information with the level of DEBUG to the two destinations of console and file
log4j.rootLogger=DEBUG,console,file

# Relevant settings of console output
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

# Relevant settings for file output
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/log.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-mm-dd}][%c]%m%n

# Log output level
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

Mybatis core profile:

<?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">

<!--  Attention in configuration In the configuration file, there are strict regulations on the location of each label  -->
<configuration>

    <!--  Import external profile  -->
    <properties resource="dp.properties" />

    <!--  Alias: easy to use in XXXMapper.xml Not used in file com.cainiao.xxxx
      Direct use xxxx-->
    <typeAliases>
        <package name="com.cainiao.pojo"/>
    </typeAliases>

    <!--  Multiple sets of environments can be configured here. They are used by default development environment  -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--  Configure multiple mappers  -->
    <mappers>
<!--        <mapper resource="com/cainiao/mapper/UserMapper.xml"/>-->
        <mapper resource="mapper/UserMapper.xml"/>
        <mapper resource="mapper/StudentMapper.xml"/>
        <mapper resource="mapper/TeacherMapper.xml"/>
        <mapper class="com.cainiao.annotationMapper.StudentAnnotationMapper"/>
        <mapper resource="mapper/BlogMapper.xml" />
    </mappers>
</configuration>

(POJO) entity class Blog:

package com.cainiao.pojo;

import java.util.Date;

public class Blog {

    private String id;
    private String title;
    private String author;
    private Date createTime;
    private String views;

    public Blog() {
    }

    public Blog(String id, String title, String author, Date createTime, String views) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.createTime = createTime;
        this.views = views;
    }

    public String getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getViews() {
        return views;
    }

    public void setViews(String views) {
        this.views = views;
    }

    @Override
    public String toString() {
        return "Blog{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", createTime=" + createTime +
                ", views='" + views + '\'' +
                '}';
    }
}

(POJO) entity class Student:

package com.cainiao.pojo;

public class Student {

    private Long sid;
    private String sname;
    private Byte sage;
    private String smaster;
    private Teacher teacher;

    public Student() {
    }

    public Student(Long sid, String sname, Byte sage, String smaster, Teacher teacher) {
        this.sid = sid;
        this.sname = sname;
        this.sage = sage;
        this.smaster = smaster;
        this.teacher = teacher;
    }

    public Long getSid() {
        return sid;
    }

    public void setSid(Long sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Byte getSage() {
        return sage;
    }

    public void setSage(Byte sage) {
        this.sage = sage;
    }

    public String getSmaster() {
        return smaster;
    }

    public void setSmaster(String smaster) {
        this.smaster = smaster;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", sage=" + sage +
                ", smaster='" + smaster + '\'' +
                ", teacher=" + teacher +
                '}';
    }
}

(POJO) entity class Teacher:

package com.cainiao.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.List;

public class Teacher {

    private String master;
    private Integer tage;
    private String tmajor;

    private List<Student> studentList;

    public Teacher() {
    }

    public Teacher(String master, Integer tage, String tmajor, List<Student> studentList) {
        this.master = master;
        this.tage = tage;
        this.tmajor = tmajor;
        this.studentList = studentList;
    }

    public String getMaster() {
        return master;
    }

    public void setMaster(String master) {
        this.master = master;
    }

    public Integer getTage() {
        return tage;
    }

    public void setTage(Integer tage) {
        this.tage = tage;
    }

    public String getTmajor() {
        return tmajor;
    }

    public void setTmajor(String tmajor) {
        this.tmajor = tmajor;
    }

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "master='" + master + '\'' +
                ", tage=" + tage +
                ", tmajor='" + tmajor + '\'' +
                ", studentList=" + studentList +
                '}';
    }
}

(POJO) entity class User:

package com.cainiao.pojo;

public class User {

    private Integer id;
    private String userName;
    private String userAge;
    private String userAddress;

    public User() {
    }

    public User(Integer id, String userName, String userAge, String userAddress) {
        this.id = id;
        this.userName = userName;
        this.userAge = userAge;
        this.userAddress = userAddress;
    }

    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 String getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }

    public String getUserAddress() {
        return userAddress;
    }

    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", userAge='" + userAge + '\'' +
                ", userAddress='" + userAddress + '\'' +
                '}';
    }
}

Mybatis core configuration file parsing tool:

package com.cainiao.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 {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        // Set autoCommit=true here to automatically submit. Different from submitting, you can manually sqlsession commit;
        return sqlSessionFactory.openSession(true);
    }
}

Generator uid:

package com.cainiao.utils;

import org.junit.Test;

import java.util.UUID;

public class IdUtils {

    public static String getId(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    @Test
    public void test(){
        System.out.println(getId());
    }
}

UserMapper.java} interface (add, delete, modify and check CRUD):

Note: all basic types need to be preceded by @ Param() method to develop specifications; The @ Param() method is not required for reference types;

Content: Based on User

(1) Query all users;

(2) Query according to user Id;

(3) Fuzzy query based on user name (concat() is used here to splice strings to prevent SQL injection);

(4) Add users;

(5) Enterprise level: if there are too many entity class attributes, you can consider using map for database insertion @ param map

(6) Delete the user according to the user id;

(7) Modify the user information according to the user id;

package com.cainiao.mapper;

import com.cainiao.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public interface UserMapper {

    /**
     * Query all users (query)
     * @return
     */
    List<User> getUserList();

    /**
     * Query by user Id
     * @param id
     * @return
     */
    User selectUserById(@Param("id") int id);


    /**
     * Fuzzy query based on user name
     * @param name
     * @return
     */
    List<User> selectUserByLike(@Param("name") String name);


    /**
     * Add user (add)
     * @param user
     */
    void addUser(User user);

    /**
     * Enterprise level: if there are too many entity class attributes, (add)
     * You can consider using map
     * Database insert operation
     * @param map
     */
    void addUserByMap(Map<String, Object> map);


    /**
     * Delete user according to user id (delete)
     * @param id
     */
    void deleteUser(@Param("id") int id);


    /**
     * Modify user information according to user id (change)
     * @param user
     */
    void updateUser(User user);


}

UserMapper. SQL information of XML corresponding interface:

<?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.cainiao.mapper.UserMapper">
    <select id="getUserList" resultType="com.cainiao.pojo.User">
        select * from user;
    </select>

    <select id="selectUserById" parameterType="int" resultType="user">
        select * from user where id=#{id};
    </select>

    <!--  use concat Fuzzy query can effectively prevent sql injection  -->
    <select id="selectUserByLike" parameterType="String" resultType="user">
        select *
        from user
        where userName like concat('%', #{name}, '%');
    </select>

    <!--  Inserted User The attribute names in the information must correspond one by one  -->
    <insert id="addUser" parameterType="user" useGeneratedKeys="true" keyProperty="id">
        insert into user values(#{id},#{userName},#{userAge},#{userAddress})
    </insert>

    <!--  Enterprise level: if there are too many entity class attributes, you can consider using it map Insert database,Heel map Key value of  -->
    <insert id="addUserByMap" parameterType="map" useGeneratedKeys="true" keyProperty="id">
        insert into user(id, userName, userAddress) values(#{defineId},#{defineUserName},#{defineUserAddress})
    </insert>

    <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id};
    </delete>

    <update id="updateUser" parameterType="user">
        update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id};
    </update>
</mapper>

StudentMapper.java} interface:

Note: all basic types need to be preceded by @ Param() method to develop specifications; The @ Param() method is not required for reference types;

Content: Based on Student

(1) Query data information based on simple < resultmap > tag;

(2) Paging query; (essentially SQL statement - limit)

package com.cainiao.mapper;

import com.cainiao.pojo.Student;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface StudentMapper {

    /**
     * resultMap is used here for query
     * @return
     */
    List<Student> selectAllStudent();

    /**
     * paging
     * @param map
     * @return
     */
    List<Student> selectStudentByPage(Map<String,Integer> map);

}

StudentMapper. SQL information of XML corresponding interface:

<?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.cainiao.mapper.StudentMapper">

    <!--  among column For fields in the database
          property Attribute fields within an entity-->
    <resultMap id="studentMap" type="student">
        <id column="sid" property="sid" />
        <result column="sname" property="sname" />
        <result column="sage" property="sage" />
        <result column="smaster" property="smaster" />
    </resultMap>

    <!--  use resultMap To query  -->
    <select id="selectAllStudent" resultMap="studentMap">
        select *
        from student
    </select>

    <!--  Paging query: essentially SQL limit Compilation of  -->
    <select id="selectStudentByPage" resultMap="studentMap">
        select *
        from student
        limit #{startPage}, #{pageSize};
    </select>

</mapper>

TeacherMapper.java} interface:

Note: all basic types need to be preceded by @ Param() method to develop specifications; The @ Param() method is not required for reference types;

Content: Based on Teacher # implementation

(1) "Many to one" joint table query;

(2) "One to many" joint table query;

package com.cainiao.mapper;

import com.cainiao.pojo.Student;
import com.cainiao.pojo.Teacher;

import java.util.List;

public interface TeacherMapper {

    /**
     * Query all information of students and teachers through the joint table (many to one)
     * @return
     */
    List<Student> getStuTeaInfo();


    /**
     * Query all information of teachers and students through the joint table (one to many)
     * @return
     */
    List<Teacher> getTeaStuInfo();

}

TeacherMapper. SQL information of XML corresponding interface:

<?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.cainiao.mapper.TeacherMapper">

    <!--  "Many to one" joint table is used here to query "student"-"Teacher" related information  -->
    <resultMap id="stuTeaMap" type="student">
        <result property="sid" column="sid" />
        <result property="sname" column="sname" />
        <result property="sage" column="sage" />
        <!--    Join table here    -->
        <association property="teacher" javaType="Teacher">
            <result property="tmajor" column="tmajor" />
        </association>
    </resultMap>
    <select id="getStuTeaInfo" resultMap="stuTeaMap">
        select s.sid sid, s.sage sage, s.sname sname, t.tmajor tmajor
        from student s, teacher t
        where s.smaster = t.`master`;
    </select>

    
    <!--  "One to many" joint table is used here to query "teacher" - "Student" related information  -->
    <resultMap id="teaStuMap" type="Teacher">
        <result property="master" column="tmaster" />
        <result property="tmajor" column="tmajor" />
        <collection property="studentList" ofType="Student">
            <result property="sid" column="sid" />
            <result property="sname" column="sname" />
            <result property="sage" column="sage" />
        </collection>
    </resultMap>
    <select id="getTeaStuInfo" resultMap="teaStuMap">
        select t.`master` tmaster, t.tmajor tmajor, s.sid sid, s.sname sname, s.sage sage
        from student s, teacher t
        where s.smaster = t.`master`
    </select>

</mapper>

BlogMapper.java} interface:

Note: all basic types need to be preceded by @ Param() method to develop specifications; The @ Param() method is not required for reference types;

Content: Based on Blog} implementation

(1) Insert Blog data;

(2) Dynamic SQL < if > is used for query;

(3) Use dynamic SQL < choose > to execute SQL statements selectively on attributes;

(4) Use dynamic SQL < set > to update the blog table;

(5) Use < foreach > for dynamic SQL query; (not commonly used, it's best to write object-oriented code);

package com.cainiao.mapper;

import com.cainiao.pojo.Blog;

import java.util.List;
import java.util.Map;

public interface BlogMapper {

    /**
     * Insert Blog data
     * @param blog
     */
    void addBlog(Blog blog);

    /**
     * Query with dynamic SQL
     * @return
     */
    List<Blog> selectBlogIF(Map<String, Object> map);

    /**
     * Use dynamic SQL < choose > to selectively execute SQL statements on attributes
     * @param map
     * @return
     */
    List<Blog> selectBlogCHOOSE(Map<String, Object> map);


    /**
     * Update blog table with dynamic SQL
     * @param blog
     */
    void updateBlog(Blog blog);


    /**
     * Dynamic SQL query using foreach
     * @param map
     * @return
     */
    List<Blog> selectBlogFOREACH(Map<String, Object> map);

}

BlogMapper. SQL information of XML corresponding interface:

<?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.cainiao.mapper.BlogMapper">

    <!--  insert Blog data  -->
    <insert id="addBlog" parameterType="blog">
        insert into blog (id, title, author, create_time, views)
        values(#{id}, #{title}, #{author}, #{createTime}, #{views})
    </insert>

    <!--  Adopt dynamic SQL <if> <where> Make a query
        // With parameters: query by parameters
        // No parameter: query all data
        Attention (key points): (1) use <where>The label can be on the back <if> Conduct inspection;
                    (2)If there are conditions, query according to the conditions;
                    (3)Query all without conditions;
     -->
    <select id="selectBlogIF" resultType="blog" parameterType="map">
        select *
        from blog
        <where>
            <if test="title != null">
                title=#{title}
            </if>
            <if test="author != null">
                and author=#{author}
            </if>
        </where>
    </select>

    <!--  dynamic SQL <choose>...<when>... Properties can be filtered and executed SQL sentence
            <choose>Label for<when> Match from top to bottom
            If the matching is successful, stop matching and select only <choose> One of <when> implement-->
    <select id="selectBlogCHOOSE" parameterType="map" resultType="blog">
        select *
        from blog
        <where>
            <choose>
                <when test="title != null">
                    title=#{title}
                </when>
                <when test="author != null">
                    and author=#{author}
                </when>
                <otherwise>
                    and views=#{views}
                </otherwise>
            </choose>
        </where>
    </select>

    <!--  set The element is dynamically inserted at the beginning of the line SET keyword,
            Note: additional commas will be deleted
            (These commas are introduced when using conditional statements to assign values to columns)  -->
    <update id="updateBlog" parameterType="blog">
        update blog
        <set>
            <if test="title != null">title=#{title},</if>
            <if test="author != null">author=#{author},</if>
            <if test="views != null">views=#{views}</if>
        </set>
        <where>
            id=#{id}
        </where>
    </update>

    <!--  Adopt dynamic SQL foreach Make a query  -->
    <select id="selectBlogFOREACH" parameterType="map" resultType="blog">
        select *
        from blog
        <where>
            <foreach collection="authors" item="author" open="(" close=")" separator="or">
                author = #{author}
            </foreach>
        </where>
    </select>

</mapper>

StudentAnnotationMapper.java} interface:

Note: the conventional XXX is not used here XML file for database data access,

Use annotation to query the database @ Select;

Simple query} can be queried using annotations; Complex database query operations {still need to use xml files to write queries;

package com.cainiao.annotationMapper;

import com.cainiao.pojo.Student;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface StudentAnnotationMapper {

    /**
     * Simple query operation with annotation
     * Note: when using annotations, you need to ensure that the entity class attributes correspond to the database fields one by one
     * @param sid
     * @return
     */
    @Select("select * from student where sid=#{sid}")
    Student selectStudentByIdAno(@Param("sid") long sid);

}

UserMapperTest test code: (Junit is used for query here, and the single test without Spring annotation is used)

UserMapperTest.java

package com.cainiao.mapper;

import com.cainiao.pojo.User;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

public class UserMapperTest {

    @Test
    void getUserListTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUserList();

        for (User user : userList) {
            System.out.println(user.getId() + "\t" + user.getUserName() + "\t" +
                    user.getUserAge() + "\t" + user.getUserAddress());
        }

        sqlSession.close();
    }

    @Test
    void selectUserByIdTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectUserById(1);

        System.out.println(user.getId() + "\t" + user.getUserName() + "\t" +
                user.getUserAge() + "\t" + user.getUserAddress());

        sqlSession.close();
    }


    @Test
    void addUserTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = new User();
        user.setUserName("Aaron1");
        user.setUserAge("20");
        user.setUserAddress("Chongqing");

        mapper.addUser(user);

        // Note: transaction submission is required for addition, deletion and modification
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    void deleteUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(8);
        System.out.println("User deleted successfully");

        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    void updateUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = new User();
        user.setId(9);
        user.setUserName("Aaron2");
        user.setUserAge("50");
        user.setUserAddress("Shiniapan");

        mapper.updateUser(user);

        // Addition, deletion and modification: transaction submission is required
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    void addUserByMap() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> map = new HashMap<>();
        map.put("defineUserName", "User1");
        map.put("defineUserAddress", "Wenquancheng");

        mapper.addUserByMap(map);

        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    void selectUserByLike() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectUserByLike("Aaron");

        for (User user : userList) {
            System.out.println(user.getId() + "\t" + user.getUserName() + "\t" +
                    user.getUserAge() + "\t" + user.getUserAddress());
        }

        sqlSession.close();
    }
}

StudentMapperTest test code: (Junit is used for query here, and the single test without Spring annotation is used)

StudentMapperTest.java

package com.cainiao.mapper;

import com.cainiao.pojo.Student;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

class StudentMapperTest {

    @Test
    void selectAllStudentTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> students = mapper.selectAllStudent();

        for (Student student : students) {
            System.out.println(student.getSid() + "\t"
                    + student.getSname() + "\t" + student.getSage()
                    + "\t" + student.getSmaster() + "\t" + student.getTeacher());
        }

        sqlSession.close();
    }

    @Test
    void testLogger(){
        Logger logger = Logger.getLogger(StudentMapperTest.class);
        logger.info("Successful entry info level");
        logger.debug("Successful entry debug level");
        logger.error("Successful entry error level");
    }

    /**
     * Test paging
     */
    @Test
    void selectStudentByPage() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        Map<String,Integer> map = new HashMap<>();
        map.put("startPage", 0);
        map.put("pageSize", 2);

        List<Student> students = mapper.selectStudentByPage(map);

        for (Student student : students) {
            System.out.println(student.getSid() + "\t"
                    + student.getSname() + "\t" + student.getSage()
                    + "\t" + student.getSmaster());
        }

        sqlSession.close();
    }
}

Student annotation mappertest test code: (Junit is used for query here, and the single test without Spring annotation is used)

StudentAnnotationMapperTest.java

package com.cainiao.mapper;

import com.cainiao.annotationMapper.StudentAnnotationMapper;
import com.cainiao.pojo.Student;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

class StudentAnnotationMapperTest {

    @Test
    void selectStudentByIdTest() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentAnnotationMapper mapper = sqlSession.getMapper(StudentAnnotationMapper.class);
        if(mapper.selectStudentByIdAno(1) == null){
            System.out.println("The result is empty");
        }else{
            Student student = mapper.selectStudentByIdAno(1);
            System.out.println(student.getSid() + "\t"
                    + student.getSname() + "\t" + student.getSage()
                    + "\t" + student.getSmaster());

            sqlSession.close();
        }
    }
}

TeacherMapperTest test code: (Junit is used for query here, and the single test without Spring annotation is used)

TeacherMapperTest.java

package com.cainiao.mapper;

import com.cainiao.pojo.Student;
import com.cainiao.pojo.Teacher;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

class TeacherMapperTest {

    @Test
    void getStuTeaInfoTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        List<Student> stuTeaInfo =
                mapper.getStuTeaInfo();
        for (Student student : stuTeaInfo) {
            System.out.println(String.valueOf(student));
        }
    }

    @Test
    void getTeaStuInfoTest() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        List<Teacher> teaStuInfo = mapper.getTeaStuInfo();

        for (Teacher teacher : teaStuInfo) {
            System.out.println(teacher);
        }

        sqlSession.close();
    }
}

BlogMapperTest test code: (Junit is used for query here, and the single test without Spring annotation is used)

BlogMapperTest.java

package com.cainiao.mapper;

import com.cainiao.pojo.Blog;
import com.cainiao.utils.IdUtils;
import com.cainiao.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;

class BlogMapperTest {

    @Test
    void addBlogTest() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        mapper.addBlog(new Blog(IdUtils.getId(), "aaaaaaaaaaaaa", "Mary", new Date(), "100"));
        mapper.addBlog(new Blog(IdUtils.getId(), "bbbbbbbbbbbbb", "Tom", new Date(), "200"));
        mapper.addBlog(new Blog(IdUtils.getId(), "ccccccccccccc", "Tony", new Date(), "58"));
        mapper.addBlog(new Blog(IdUtils.getId(), "ddddddddddddd", "Aaron", new Date(), "355"));

        sqlSession.close();
    }

    @Test
    void selectBlogIFTest() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        // With parameters: query by parameters
        // No parameter: query all data
        Map<String, Object> map = new HashMap<>();
//        map.put("title", "bbbbbbbbbbbbb");
        List<Blog> blogs = mapper.selectBlogIF(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }

    }

    @Test
    void selectBlogCHOOSE() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Map<String, Object> map = new HashMap<>();
//        map.put("title", "bbbbbbbbbbbbb");
        map.put("author", "Mary");
        map.put("views", "58");

        List<Blog> blogs = mapper.selectBlogCHOOSE(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();

    }

    @Test
    void updateBlog() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Blog blog = new Blog();
        blog.setTitle("ddddddddddddd1");
        blog.setAuthor("Aaron1");
        blog.setId("45a5fa1f5e4f41599b72ae1950257e6c");
        mapper.updateBlog(blog);

        sqlSession.close();

    }

    @Test
    void selectBlogFOREACH() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Map<String, Object> map = new HashMap<>();
        ArrayList<String> authors = new ArrayList<String>();
        authors.add("Tony");

        map.put("authors", authors);
        List<Blog> blogs = mapper.selectBlogFOREACH(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();
    }
}

Keywords: Java JavaEE Mybatis intellij-idea

Added by hesketh on Sun, 20 Feb 2022 14:15:42 +0200