MyBatis-01 - first met MyBatis

1, Introduction

1.1 what is MyBatis

  • brief introduction
    • MyBatis is an excellent persistence layer framework, which supports custom SQL, stored procedures and advanced mapping.
    • MyBatis eliminates almost all JDBC code and the work of setting parameters and obtaining result sets.
    • MyBatis can configure and map primitive types, interfaces and Java POJO s (Plain Old Java Objects) to records in the database through simple XML or annotations.
  • characteristic
    • Easy to learn: it is small and simple in itself. 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. Through documents and source code, you can fully master its design idea and implementation.
    • Flexibility: mybatis does not impose any impact on the existing design of the application or database. sql is written in xml to facilitate unified management and optimization. All the requirements of operating the database can be met through sql statements.
    • Decouple sql and program code: separate business logic and data access logic by providing DAO layer, so as to make the design of the system clearer, easier to maintain and easier to unit test. The separation of sql and code improves maintainability.
    • Provide mapping labels to support the mapping between objects and orm fields in the database
    • Provide object relationship mapping labels to support the establishment and maintenance of object relationships
    • Provide xml tags to support writing dynamic sql
  • Official documents
  • Github

1.2 persistence and persistence layer

1. Persistence

  • What is persistence?
    • Persistence is a mechanism to convert program data between persistent state and transient state.
      • Simply put, it is to save the data in memory on external memory
  • Why persist?
    • The breakpoint or loss of memory determines that memory cannot store data for a long time
    • Although we can ensure that a server runs 7 * 24, in case of an accident, all the data without persistence will be lost

2. Persistent layer

  • What is persistence layer?

    • The logical layer dedicated to persistence operation, which operates the database layer uniformly

1.3 why use MyBatis

  • More people use it, more people use it, which means it must be excellent. If it's not excellent, why do more people use it

  • It simplifies the traditional JDBC operation and improves the development efficiency

  • All things can still be done without Mybatis, but with it, all the implementation will be easier!

    There is no distinction between high and low technology, only the people who use it

2, Hello MyBatis

2.1 setting up test environment

  • Establish test database

    CREATE TABLE `user` (
      `name` varchar(20) DEFAULT (NULL),
      `pwd` varchar(20) DEFAULT ('123456'),
      PRIMARY KEY (`id`)
    INSERT INTO `mybatis`.`user`(`name`, `pwd`) 
    VALUES ('Li Si', '12345'),('Zhang San','1234'),('bruce','root');
  • Import MySQL and MyBatis dependencies in maven

    <!--MySQL drive-->
    <!-- -->
    <!-- -->
  • Create core profile

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

2.2 preparation

  • Create MyBatis tool class

    • Used to build SqlSessionFactory. SqlSession in MyBatis provides all the methods required to execute SQL commands in the database. We can directly execute the mapped SQL statements through the SqlSession instance
    package com.pbx.utils;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
     * @author BruceXu
     * @date 2020/10/30
    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) {
        public static SqlSession getSqlSession() {
            return sqlSessionFactory.openSession();
  • Create entity class

    package com.pbx.pojo;
     * @author BruceXu
     * @date 2020/10/30
    public class User {
        private int id;
        private String name;
        private String pwd;
        public User() {
        public User(int id, String name, String pwd) {
   = id;
   = name;
            this.pwd = pwd;
        public int getId() {
            return id;
        public void setId(int id) {
   = id;
        public String getName() {
            return name;
        public void setName(String name) {
   = name;
        public String getPwd() {
            return pwd;
        public void setPwd(String pwd) {
            this.pwd = pwd;
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", pwd='" + pwd + '\'' +
  • Write Mapper interface

    package com.pbx.mapper;
    import com.pbx.pojo.User;
    import java.util.List;
     * @author BruceXu
     * @since 2020/10/30
    public interface UserMapper {
        List<User> getUsers();

2.3 coding

  • Write mapper XML configuration file

    • The namespace should be consistent with the package name of the mapper interface file
    • id should correspond to the function name provided in the mapper interface on
    • resultType represents the return value of the SQL statement
    • parameterType indicates the parameter type to be received in the corresponding method
    • If you need to pass parameters, you can use #{} to represent placeholders. Moreover, the permission modifier in the entity class can be ignored, and the attributes can be extracted directly
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-// Mapper 3.0//EN"
    <mapper namespace="com.pbx.mapper.UserMapper">
        <select id="getUsers" resultType="com.pbx.pojo.User">
        select * from mybatis.user
  • In mybatis config Register UserMapper in XML

        <mapper resource="com/pbx/mapper/Mapper.xml" />

2.4 testing

  • Write test class

    package com.pbx.mapper;
    import com.pbx.pojo.User;
    import com.pbx.utils.MyBatisUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    import java.util.List;
     * @author BruceXu
     * @date 2020/10/30
    public class TestUserMapper {
        public void test() {
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> list = mapper.getUsers();
            for (User user : list) {
  • test run

    • The following error occurred during operation

    • The error reason is as follows: error parsing SQL mapper configuration Cause: java. io. IOException: Could not find resource com/pbx/mapper/Mapper.xml, unable to find our mapper XML file. But after observing the project structure, I found that, ah, mapper XML files are available. Why can't you find them?

      • The reason for this problem is that there is a problem in the export of maven static resources. We need to adjust the filter conditions of static resources to enable maven to filter them
    • Solution: modify maven's static resource filtering

    • After modification, you can get the correct output results

2.5 general steps for using MyBatis in Maven

  1. Import the corresponding database driver and MyBatis dependency
  2. Write mybatis config XML main configuration file
  3. Building SqlSessionFactory
  4. Create entity class
  5. Create mapper interface and write mapper XML to implement SQL operations
  6. In mybatis config Configure mapper.xml for registration XML file
  7. Use
  • be careful
    • Each thread should have its own SqlSession instance.
    • The instance of SqlSession is not thread safe, so it cannot be shared, so its best scope is the request or method scope.
    • Never put the reference of SqlSession instance in the static field of a class, or even the instance variable of a class.
    • You must never put the reference of SqlSession instance in any type of managed scope, such as HttpSession in Servlet framework.
    • If you are currently using a Web framework, consider putting SqlSession in a scope similar to HTTP requests.
    • In other words, every time you receive an HTTP request, you can open a SqlSession and close it after returning a response
    • Not only in web applications, every time a SqlSession runs out, it must be closed

Tags: Mybatis

Posted by IceD on Mon, 09 May 2022 02:07:59 +0300