Mybatis learning diary 01 ~ 02

1. Get to know Mybatis

1.1 what is Mybatis and its purpose:

1.MyBatis is an excellent persistence layer framework

2.MyBatis usage: it eliminates almost all JDBC code and the work of setting parameters and obtaining result sets.

3.MyBatis can configure and map primitive types, interfaces and Java POJO s through simple XML or annotations

The Chinese documents used in the official help and the download address of GitHub are as follows (you can also search on GitHub and click releases to download):

1.2 persistence:

Persistence is a mechanism to convert program data between persistent state and transient state.

  • That is to save data (such as objects in memory) to a permanent storage device (such as disk). The main application of persistence is to store the objects in memory in the database, or in disk files, XML data files and so on.

  • JDBC is a persistence mechanism. File IO is also a persistence mechanism.

Why do you need persistence services? That is caused by the defect of memory itself

  • Data will be lost after memory power failure. Some important objects need to be saved continuously

  • Memory is too expensive

1.3 durable layer:

  • Code block to complete persistence. --- > Dao layer

  • In most cases, especially for enterprise applications, data persistence often means saving the data in memory to disk for solidification, and the implementation process of persistence is mostly completed through various relational databases.

  • However, there is a word that needs special emphasis, that is, the so-called "layer". For application systems, data persistence is an essential part. In other words, our system has a natural concept of "persistence layer"? Maybe, but maybe that's not the case. The reason why we want to separate the concept of "persistence layer" instead of "persistence module" and "persistence unit" means that there should be a relatively independent logical level in our system architecture, focusing on the implementation of data persistence logic

  • Compared with other parts of the system, the boundary of the layer is very obvious [it exists for operating the database]

1.4 why do you need Mybatis

  • Mybatis is to help the program store data in the database and get data from the database

  • The traditional jdbc operation has many repeated code blocks, such as the encapsulation of data extraction, the establishment of database connection, etc. through the framework, the repeated code can be reduced and the development efficiency can be improved

  • MyBatis is a semi-automatic ORM framework (object relationship mapping) - > object relationship mapping

  • All things can still be done without Mybatis, but with it, all the implementation will be easier! There is no difference between high and low technology, only the people who use it

2. The first MyBatis program  

2.1 preparations before commencement

1. First, create a common Maven project, connect to the database, and import the required basic mysql and mybatis and junit dependencies in pom.xml

    <!--Import dependency-->
        <!-- -->


        <!-- -->


2. Because the object of SqlSessionFactor1 is required, three lines of code are provided in the official document

  These three lines of code are used every time. We extract them into a public class named MybatisUtils under the utils package

package com.kuang.utils;

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


//sqlSessionFactory --> sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;
        try {
            //The first step of using mybatis is to obtain the sqlSessionFactory object
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {

    // Now that we have SqlSessionFactory, as the name suggests, we can get an instance of SqlSession from it.
    // Session completely includes all the methods required to execute SQL commands facing the database, just like the Preparedstatement object in JDBC
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();


3. Write his configuration file (also on the official website) under mybatis-config.xml defined under resources. You only need to modify the option parameters in it

The following are the author's parameters (because the database used by the author is 8.x, the driver has cj, and the time zone needs to be designed). You can modify them according to your own parameters

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-// Config 3.0//EN"
<!--configuration Core profile-->
    <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?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>

    <!--every last Mapper.XML All need to be in Mybatis Register in core profile-->
        <mapper resource="com/kuang/dao/UserMapper.xml"/>

2.2 perform routine operations

1. Write entity classes under pojo related to database

2. Write the interface of entity class under dao layer, such as UserMapper

2.3 replace the original JDBC interface implementation class with Mapper.xml file

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<!--namespace=Bind a corresponding Dao/Mapper Interface-->
<mapper namespace="com.kuang.dao.UserMapper">
    <!--id The method tag body corresponding to the binding focuses on sql Writing return value types focuses on return values
    No more writing resultset To traverse the interface object obtained by directly calling reflection during test getUserList method
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user

2.4 code testing

1. Test under this green java. The package and class names corresponding below should preferably be consistent with the package and class names written by the program

2.1 step 1: get SqlSession object

2.2 call the getMapper method in the object, where the parameter is to obtain the Class object by reflection, and an interface object will be returned

2.3 call the method of the interface defined by myself. What the author defines is getUserList(), which is used to traverse the output

2.4 in order to ensure that all database resources can be shut down correctly, try finally is used to optimize the code

package com.kuang.dao;

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 UserMapperTest {

    public void test(){
        //Step 1: get SqlSession object
        SqlSession sqlSession = MybatisUtils.getSqlSession();;

            //Method 1: getMapper
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = userMapper.getUserList();

            //Method 2: it is not recommended, because if the write is dead, List will return List, and Map will return Map, which will be returned according to the return value of the method
            // List<User> userList = sqlSession.selectList("com.kuang.dao.UserDao.getUserList");

            for (User user : userList) {
            //Close SqlSession

3. Write the Bug encountered in the first Mybatis program and its handling method

1.Cannot access com.kuang.dao.User

When writing the UserMapper interface under the dao layer, the author has been unable to import the User entity class under the pojo package

When the automatic package guide operation is checked, the package can not be imported under the same project

Restart the IDEA in file - > invalidate cache to resolve this error


2. Error of java.lang.ExceptionInInitializerError during test

1. Check whether static resources are released

Since Maven's convention is greater than configuration, the configuration file is best placed under the resources package

Because I learned to follow the teacher's course and put it under the java package, there will be Maven static resource filtering problems,

Therefore, you need to configure the following code in the pom.xml of the parent project (to prevent unsuccessful configuration, you can also configure it in the pom.xml file of the child project)

  <!--stay build Medium configuration resources,To prevent the failure of resource export-->

At this time, the configuration file of UserMapper.xml will appear in the dao layer under target - > class during the test (if it is unsuccessful, you can refresh Maven)

2. Is there an error in the configuration file of mybatis

  3. Errors encountered by friends in online class comment area:

  The xml file cannot contain Chinese. Remove the utf-8 horizontal bar in the first line

Keywords: Java Mybatis Back-end

Added by andrewcy on Sat, 06 Nov 2021 11:18:36 +0200