Introduction and use of MyBatis

Posted by mbrown on Mon, 11 Oct 2021 23:32:58 +0200

1. Official documents of mybatis

Mybatis – MyBatis 3 | getting started

2. Why do you need Mybatis

  • Simplify the traditional JDBC code and realize automatic mapping
  • Simple and easy to use
  • Most companies use it
  • advantage:
  • Easy to learn: itself is small and simple. There is no third-party dependency. The simplest installation is as long as two jar files + several sql mapping files are configured. It is easy to learn and use. You can fully master its design idea and implementation through documents and source code.
  • Flexibility: mybatis does not impose any impact on the existing design of the application or database. sql is written in xml for unified management and optimization. All requirements for operating the database can be met through sql statements.
  • Decouple sql and program code: by providing DAO layer, separate business logic and data access logic, so as to make the system design clearer, easier to maintain and easier to unit test. The separation of sql and code improves maintainability.
  • Provide mapping labels to support the mapping of orm fields between objects and databases
  • Provide object relationship mapping labels to support object relationship construction and maintenance
  • Provide xml tags to support writing dynamic sql.

3. The first Mybatis program

(1) 1. Build database

(2) . create project import dependency

Import mybatis and MySQL connector Java dependencies

Create a module on the project name (e.g. 20211011) and import dependencies in the automatically generated second pom file (you can also get them in the first pom file, but add < parent >)


(3) . write the configuration file mybatis-config.xml under resources

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-// Config 3.0//EN"
<!--Core profile-->
    <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/yhzzuseUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
        <mapper resource="mapper/UserMapper.xml"/>
<!--You can find it on the official website-->

(4) 1. Writing tool classes

package com.yhzz.util;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisUtils {
private static SqlSessionFactory factory;

        try {
            String resource = "mybatis-config.xml";
            InputStream resourceAsStream =Resources.getResourceAsStream(resource);
            factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            } catch (IOException e) {
    //Get SqlSession object
public static SqlSession getSqlSession(){
    return factory.openSession();

(5) . write entity classes and interfaces, "implementation classes", and test

① Create an entity class user under pojo

  ② UserMapper interface

package com.yhzz.dao;
import com.yhzz.pojo.User;
import java.util.List;

public interface UserMapper {
    List<User> getUserList();

③ Mapper corresponding xml file (UserMapper.xml)

  • Note that the file name and path must be the same as the Mapper path of the last configuration in our first XML configuration file: mybatis-config.xml.


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-// Mapper 3.0//EN"
    <mapper namespace="com.yhzz.dao.UserMapper">
    <select id="getUserList" resultType="com.yhzz.pojo.User">
        select * from user;

  ④ Write the BaseDaoUtil class in util

⑤ Write a test class, create a test under the main file, right-click -- > mark directory as to turn green, and then create a UserMapperTest class  

public class UserMapperTest {
    public void queryUserList(){
        //Get sqlsession object
        SqlSession sqlSession = BaseDaoUtil.openSqlSession();
        //Get userMapper object
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //Call method to execute sql
        List<User> userList = mapper.queryUserList();
        for (User user :userList){

  4. When Map is used as a parameter

//Modify user
public void user(){
        //Get sqlsession object
        SqlSession sqlSession = BaseDaoUtil.openSqlSession();
        //Get userMapper object
        UserMapper mapper =sqlSession.getMapper(UserMapper.class);
        Map<String,Object> map = new HashMap();//New map object
        map.put("username","Ma Liu");
        map.put("pwd","3");//Stored value
        User user = mapper.user(map);
        sqlSession.close();//close resource
//For addition, deletion and modification, the transaction sqlSession.commit() must be submitted manually;

  sql statement in UserMapper.xml file

<!--    Query user-->
    <select id="user" parameterType="map" resultType="user">
        select * from user where id = #{id} and username = #{username} and pwd = #{pwd}

5. Fuzzy query

sql statement in UserMapper.xml file

<select id="queryLikeUser" resultType="user" parameterType="map">
        select * from user where userName like "%"#{userName}"%";

Topics: Java Database Mybatis SQL unit testing