Mybatis implements simple CRUD principle and example analysis notes [Full]

Keywords: SSM

Mybatis implements simple CRUD (addition, deletion, modification and query)

Database used:

USE `mybatis`;
  `id` int(20) NOT NULL,
  `name` varchar(30) DEFAULT NULL,
  `pwd` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
insert  into `user`(`id`,`name`,`pwd`) values (1,'Reliable poplar','123456'),(2,'Zhang San','abcdef'),(3,'Li Si','987654');

Before using, import the Mybatis dependency package in Maven


The official MyBatis core configuration file mybatis-config.xml

<?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?	
                <property name="username" value="root"/>
                <property name="password" value="000429"/>
        <mapper resource="com/kuang/dao/userMapper.xml"/>

be careful


It is likely that an error will be reported here. Maven needs to solve the problem of static resource filtering. Maven is used to the principle of greater than configuration

Add the following code to pom.xml file:


Note: refresh maven after configuration!

Simple data type

package com.kuang.pojo;
public class User {
	private int id;  //id
	private String name;   //full name
	private String pwd;   //password
	//Structure, with and without parameters

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

	public User(){}
	public int getId() {
		return id;

	public void setId(int id) { = id;

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

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String getPwd() {
		return pwd;

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

Data interface layer

public interface UserMapper {
	//Query all users
	List<User> getUserList();
	//Query user by ID
	User getUserByID(int id);
	//insert a user
	int addUser(User user);
	//update a user
	int updateUser(User user);
	//delete a user
	int deleteUser(User user);

User defined userMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<mapper namespace="com.kuang.dao.UserMapper">
    <select id="getUserList" resultType="com.kuang.pojo.User">
    select * from user
    <select id="getUserByID" resultType="com.kuang.pojo.User" parameterType="int">
    select * from user WHERE id = #{id}
    <!--The properties in the object can be extracted directly -->
    <insert id="addUser" parameterType="com.kuang.pojo.User">
        insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});

    <update id="updateUser" parameterType="com.kuang.pojo.User">
        update mybatis.user set name = #{name} , pwd=#{pwd} where id = #{id} ;
    <delete id="deleteUser" parameterType="com.kuang.pojo.User" >
        delete from mybatis.user where id = #{id}

Here, we can find that the data interface corresponds to xml. The xml file instances the interface and the methods in it. The namespace is the name of the interface, the select tag in it corresponds to a method in the interface, the id is the method name, and the resultType corresponds to the return value type of the method.

The package name of the xml file namespace should be consistent with the Dao/Mapper interface class name!

  • id (getUserList): is the method name in the corresponding namespace (List getUserList();)
  • resultType: is the return value after the SQL statement is executed! (Class, basic data type)
  • parameterType: parameter type!
  • delete from mybatis.user where id = #{id} analyze this sql statement. The assignment method is different from JDBC. The parameter in this format #{} is this method parameter. The member attribute ID in the User object can be directly put here!

The configuration tool class ( obtains the connection object:

package com.kuang.utils;

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


public class MybatisUtils {
	//Obtain an instance of SqlSession from SqlSessionFactory. SqlSession completely contains the execution method of SQL commands
	private static SqlSessionFactory sqlSessionFactory;
	static {
		try {
			String resource = "mybatis-config.xml";
			InputStream inputStream = Resources.getResourceAsStream(resource);
            //Read configuration file to get connection
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
	//Returns the obtained SqlSession connection
	public static SqlSession getSession(){
		return sqlSessionFactory.openSession();

Analyze this tool class:

First, the SqlSessionFactory class is a factory class that can generate PreparedStatement objects obtained from traditional JDBC methods. That is, to complete the same task as JDBC utils, the tool class first obtains the connection with the database. The first step is to read the mybatis-config.xml file configured by the user to obtain a database connection object, and then use this object to obtain an object of SqlSession class similar to PreparedStatement object.

The specific calling method ( is given below:

import com.kuang.dao.UserMapper;
import com.kuang.pojo.User;
import com.kuang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
	public void test(){
		//The sqlSession object is equivalent to a JDBC PreparedStatement object, which can execute sql statements
		//What we are doing now is: get the database connection, get the sqlSession object, and use this object to implement the data operation interface we defined
		//UserMapper, this interface executes specific methods with SQL statements by parsing the userMapper.xml file defined by us.
		SqlSession sqlSession = MybatisUtils.getSession();
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//		List<User> userList = mapper.getUserList();
//		for (User user : userList)
//		{
//			System.out.println(user);
//		}
		//Get by ID
		/*User user=mapper.getUserByID(1);
		//Update a piece of data with id 1
//		updateUser();
		//Delete a user
	public void addUser(){
		SqlSession sqlSession = MybatisUtils.getSession();
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		//Insert a piece of data
		User user = new User(4, "name", "password");
		int res = mapper.addUser(user);
		if (res>0){
			System.out.println("Insert succeeded!");
		//Commit transaction
	public void updateUser(){
		//Get the object connecting the coon and executing the sql statement, which is similar to the PreparedStatement of JDBC
		SqlSession sqlSession = MybatisUtils.getSession();
		//Implement UserMapper interface through reflection mechanism
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = new User(1, "Modified name", "resetpass01");

	public void deleteUser(){
		//Get connection
		SqlSession sqlSession = MybatisUtils.getSession();
		//Implementation interface
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//After implementing the interface, the mapper calls its own methods to execute sql statements
		userMapper.deleteUser(new User(1,"sss","123"));

Analyze these two lines of code:

	SqlSession sqlSession = MybatisUtils.getSession();
	UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  • The first line of code obtains an sqlSession object through the getSession method of the MybatisUtils class. This object is an object that can execute sql statements (similar to the PreparedStatement object of JDBC) that has been connected to the database
  • This is not enough. It just stays at the tool class level. The next thing to do is to let this tool class implement the user-defined data layer interface, so that the corresponding sql statements can be executed according to the user-defined data operation methods, and then the corresponding result set can be obtained.

Posted by numtre on Mon, 01 Nov 2021 10:48:00 -0700