An article introduction to Mybatis (with mind map)

Article Directory

Three-tier architecture

The three-tier architecture contains three layers:

Interface layer, business logic layer, data access layer

  • Three-tier responsibilities
  1. Interface layer: The main function room accepts user data and displays the processing results of the request. Using the web interface to interact with users, the mobile app is also recognized by Biao Aoshi, the user operates in the app, and the business logic is processed on the server side
  2. Business logic layer: receive the passed data, check the data, calculate the business logic, call the data access layer to get the data
  3. Data access layer: Dealing with the database. It mainly realizes the addition, deletion, modification and checking of data. The data in the database is submitted to the business layer, and the business layer processing transaction data is saved to the database

Three-layer corresponding package:

  • Page layer: controller
  • Business logic into: service package
  • Data access layer: dao package

Interaction of classes in the three layers

User interface layer -> business logic layer -> data access layer (persistence layer) -> database (mysql)

Three-tier corresponding processing framework

Page layer-------servlet----springmvc

Business logic layer------service class-------spring

Data access layer-------dao class---------mybatis

Frame concept

Frame is a template


  1. Stipulates some terms, content
  2. Add your own stuff

The framework is some software, semi-finished software, and some basic functions have been defined. The functions that need to be added to you are complete software. Its basic function room is reusable and upgradeable.

Framework features:

  1. Frameworks are generally not omnipotent and cannot do everything
  2. The framework is effective in a certain field, and one aspect of its specialty. For example, mabatis is strong in database operations, but it cannot do other things.
  3. The frame is a piece of software

mybatis framework definition:

A framework, called ibaatis in the early days, and the code is on github.

mybatis is mybatis SQL Mapper Framework for java (SQL mapping framework)

sql mapper: sql mapping

You can map a row of data in the database table to a java object

A row of data can be regarded as a java object. Operating this object is equivalent to operating the data in the table

dataaccess object (DAOs): data access, perform additions, deletions, and changes to the database

What functions does mybatis provide:

  1. Provides the ability to create Connection, Statement, and Resulset, without the developer creating these objects
  2. Provides the ability to execute sql statements without you having to execute sql
  3. Provides the ability to loop sql, convert sql results into java objects, and list collections
  4. Provides the ability to close resources without you having to close Connection, Statement, ResultSet

What the developer does is: provide SQL statements

Finally: the developer provides the SQL statement-mybatis handles sql-the developer gets the list collection or java object

Summary "Mybatis is a SQL mapping framework. It provides database operation capabilities and enhanced JDBC. Using mybatis allows developers to concentrate on writing SQL, without worrying about the creation and destruction of Connection, Statement, and ResultSet.

getting Started

Download mybatis

mapper file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<mapper namespace="com.bjpowernode.dao.StudentDao">
    <select id="selectStudents" resultType="com.bjpowernode.domain.Student">
        select id,name,email,age from student order by id


sql映射文件:写sql语句的,mybatis 执行这些sql
       <!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"

        3.mapper 是当前文件的根标签,必须的
        <update>:表示更新数据库的操作,就是<update>标签中,写的是update sql语句


mybatis file

<?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/springdb"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
    <!--sql mapper(sql映射文件)的位置-->
            从类路径开始的路径信息. (可以有多个)
        <mapper resource="com/bjpowernode/dao/StudentDao.xml"/>


   <!DOCTYPE configuration
        PUBLIC "-// Config 3.0//EN"


Problem: The xml file is not compiled under target.classes

First check the pom.xml file to see if there is:


Make sure the folder is in this format


Operation maven

Insert picture description here
  1. Reconstruction project
Insert picture description here
  1. Clear cache
Insert picture description here
Insert picture description here

Try to run these steps every time, and you won't need it after running successfully.

The final way: if the above are not working, copy directly to the target folder

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-P4I1Qky6-1622708095645)(C:\Users\14505\AppData\Roaming\Typora\typora-user-images\ image-20210527111433829.png)]

mybatis debug log

        <setting name="logImpl" value="STDOUT_LOGGING"/>

Introduction of main categories

Resources: a class in mybatis, responsible for reading the main configuration file

InputStream in = Resources.getResourceAsStream("mybatis.xml")

SqlSessionFactoryBuilder: Create sqlSessionFactory object,

SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

//Create SqlSessionFactory object

SqlSessionFactory : a heavyweight object, the program takes a long time to create an object and uses more resources. In the entire project, one is enough.

SqlSessionFactory: interface, interface implementation class: DefaultSqlSessionFactory

SqlSessionFactory function: get the SqlSession object.

SqlSession SqlSession = factory.openSession();

openSession() method description:

openSession(): Without parameters, get the SqlSession object of the non-auto commit transaction


openSession(true) Get the SqlSession that automatically commits the transaction

openSession(false) Get the SqlSession of the non-autocommit transaction


SqlSession interface: defines methods to manipulate data such as seletctOne(), selectList(), insert(), update(), dalete(), commit(), rollback()

The implementation class of the sqlSession interface, DefaultSqlSession,

Usage requirements: The SqlSession object is not thread-safe and needs to be used inside the method. Before executing the sql statement, use openSession() to obtain the SqlSession object. After executing the sql statement, you need to close it and execute SqlSession.close(), so It can be guaranteed that its use is thread-safe.

Dynamic agent condition analysis

List studentList = dao.selectStudents(); call

The dao object, the type is studentDao, and the fully qualified name is: com.bjpowernode.dao.StudentDao. The permission name and namespace are the same

Method name, selectStudents, this method is the id value selectStudents in the mapper file

The return value of dao methods can also determine the method SqlSession method to be called by mybatis

If the return value is a list, the SqlSession.selectList() method is called

If the return value is int, or is not a list, look at the label in the mapper, and the corresponding method of SqlSession will be called

Dynamic proxy of mybatis: Mybatis obtains the information of executing SQL statements according to the method call of Dao. Mybatis creates an implementation class of Dao interface according to your Dao interface, and creates the object of this class, completes the SqlSession call method, access database

Dynamic proxy:

StudentDao dao = SqlSession.getMapper(dao接口.class)获取这个dao接口的对象

Use mybatis dynamic proxy mechanism, use SqlSession.getMapper (dao interface)

getMapper can get the implementation class object corresponding to the dao interface

In-depth understanding of parameters

In the sql statement passed in the mapper file from the java code

parameterType: an attribute in the mapper file. Represents the data type of the parameter of the method in the dao interface. For example, the StudentDao interface is not mandatory

Simple type: In mybatis, the basic parameter type and String type in java are called simple types. To get the value of a parameter of a simple type in the mapper file, use #{any character}

Principle of parameter transfer:

 使用#{}之后,mybatis 执行sql语句是使用的jabc中的PreparedStatement对象
       String SQL = "select id,name,email,age from student where id = ?"
       PrepareStatement pst = new PrepareStatement(sql);
    2.执行sql封装为resultType = "com.bjpowernode.domain.Student"这个对象
       ResultSet rs = ps.executeQuery();

Multiple parameters:

  1. Use @Parm to name parameters

Interface public List selectMulitParam(String name,Integer age)

Use @Param("parameter name") String name

mapper file:

    select * from student where name = #{myname} or age = #{myage}

Use object method to pass

           使用对象的语法:#{属性名,javaType=类型名称,jdbcType=数据类型}   很少用
           例如:#{paramName,javaType = java.lang.String,jdbcType=VARCHAR}


    <select id="selectMultiObject" resultType="com.bjpowernode.domain.Student">
        select id,name,email,age from student where id = #{paramName,javaType=java.lang.String,jdbcType=VARCHAR}
                                                 or age = #{paramAge,javaType=java.lang.Integer,jdbcType=INTEGER}


Pass parameters by location (understand)

Map parameter transfer (poor readability, not recommended)

# And $

# : Placeholder : tell mybatis to use the actual parameter value instead. And use the PrepareStatiment object to execute the SQL statement, #{...} instead of the SQL statement?. This is safer and faster

#Result: select id,name,email,age from studetn where id =?

** ∗ ∗ : ∗ ∗ 字 符 串 替 换 ∗ ∗ : 告 诉 m y b a t i s 使 用 **:**字符串替换**:告诉mybatis使用 ∗ ∗:∗∗Character character string for changing∗∗:Advertisement v m Y B A T I S making useThe included "string" replaces the location. Use Statement to connect the sql statement with the content of ${}. It is mainly used to replace table names, column names, and sorting of different columns.

The result of $: select id, name, email, age from studetn where id = 1001

The Statement object is used to execute SQL, which is less efficient than PreparedStatement

When you are sure that the data is safe, you can use $

The difference between # and $ (emphasis):

  1. #: Use? Do placeholders in sql statements, use PreparedStatement to execute sql, high efficiency
  2. #: Can avoid sql injection, more secure
  3. $: does not apply to placeholders, it is a string connection method, using the Statement object to execute SQL, which is inefficient
  4. $: There is a risk of SQL injection and lack of security.
  5. $: can replace table name or column name

Encapsulate mybatis output results

mybatis executed the sql statement and got the java object

resultType result type, refers to the data converted to java objects after the sql statement is executed

Processing method:

  • Mybatis executes the sql statement, and then mybatis calls the parameterless construction method of the class to create the object
  • Mybatis pays the specified column value of the ResultSet to the attribute of the same name
<select id="selectMutiPosotion" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student

Peer JDBC:

ResultSet rs = executeQuery("select id,name,email,age from student");
    Student student = new Student();


resultType result type, which means that after the SQL statement is executed, the data is converted to a java object, and the java type is arbitrary

The other value of resultType result type, 1. The fully qualified name of the type 2. The alias of the type, for example, the alias of java.lang.Integer is int

Define the alias of a custom type

  1. Defined in the mybatis main configuration file to define aliases
  2. You can use custom aliases in resultType
<!--        <typeAlias type="com.bjpowernode.domain.Student" />-->
<!--        <typeAlias type="com.bjpowernode.vo.ViewStudent" alias="vstu"/>-->
        <package> name是包名,这个包中的所有类,类名就是别名(类名不区分大小写)
        <package name="com.bjpowernode.domain.Student"/>
        <package name="com.bjpowernode.vo.ViewStudent"/>


resultMap: result mapping, specify the corresponding relationship between the column name and the attribute of the java object.

  1. You define which attribute the column value is assigned to
  2. When your column name and attribute name are different, be sure to use resultMap
<resultMap id="studentMap" type="com.bjpowernode.domain.Student">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="email" property="email"/>
        <result column="age" property="age"/>
    <select id="selectAllStudents" resultMap="studentMap">
        select id,name,email,age from student

The resultMap can be reused.

Do not use resultMap and resultType together, choose one of the two

Another way to use different attributes of resultType, use as to alias

like query

  1. Prepare "% Zhang%" in advance;
  2. Or prepare "%" #{name} "%" in the mapper file

Dynamic SQL

Dynamic sql: The content of sql changes, and different sql statements can be obtained according to conditions.

Mainly the where part has changed.

The implementation of dynamic sql uses the tags provided by mybatis,

It's conditional


​ Part of the SQL statement

Used to contain multiple. When multiple IDs are established, a where keyword will be automatically added, and the redundant and or in the if will be removed.

Loop the array in Java, the list collection, mainly used in the in statement of sql

For example, three students whose student id is 1001, 1002, 1003

select * from student where id in (1001,1002,1003)

collection: indicates the type of method parameters in the interface, if it is an array, use array, if it is a list collection, use list

item: custom variables that represent array and collection members

open: the character at the beginning of the loop

close: the character at the end of the loop

separator: the separator between set members

    <select id="selectForeachOne" resultType="com.bjpowernode.domain.Student">
        select * from student where id  in
         <foreach collection="list" item="myid" open="(" close=")" separator=",">

 <select id="selectForeachTwo" resultType="com.bjpowernode.domain.Student">
        select * from student where id in
        <foreach collection="list" item ="stu" open="(" close=")" separator=",">

Two corresponding methods

    public void testselectStudentForeachOne() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        Student stu = new Student(1001, "张三", "[email protected]", 25);
        List<Integer> list = new ArrayList<>();

        List<Student> student = dao.selectForeachOne(list);
        for (Student student1 : student) {
            System.out.println("foreach---one===" + student1);

    public void testselectStudentForeachTwo() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        Student stu = new Student(1001);
        Student stu2 = new Student(1002);
        List<Student> list = new ArrayList<>();

        List<Student> student = dao.selectForeachTwo(list);
        for (Student student1 : student) {
            System.out.println("foreach---one===" + student1);

The sql code snippet is to reuse some grammar


  1. First sql statement, table name, field, etc.
  2. Just use it

Main configuration file

transactionManager: the way mybatis commits transactions and rolls back transactions

type: the type of transaction processing

  1. JDBC: Indicates that the bottom layer of mybatis is to call the Connection object in JDBC, commit, rollback
  2. MANAGED: Delegate the affairs of mybatis to other containers (a server software, a framework (spring))

DataSource: Represents the data source. In the java system, all data sources that implement the javax.sql.DataSource interface are specified. The data source represents the Connection object

type: Specify the type of data source

POOLED : Use connection pool, mybatis return piece PooledDataSource class

UNPOOLED: Every time you execute a sql statement, first create a connection, execute sql, and then close the connection

mybatis will create an UnPooledDataSource to manage the use of Connection objects

JNDI: java naming and directory service (similar to windows registry)

Property profile of the database

Put the connection information of the database in a separate file. Separate from the main configuration file of mybatis, the purpose is to facilitate modification, storage, and processing of information from multiple databases

Define a property configuration file in the resources directory,, such as

In the attribute configuration file, define the data, the format is key=value

key: general use, do multi-level directories

For example: jdbc.mysql.driver, jdbc.driver, mydriver



In the main configuration file of mybatis, use the location of the specified file, where the value needs to be used, $(key)

How to specify multiple mapper files

Write multiple tags, write as many as there are

Use package name

All xml files in this package can be loaded into mybatis at once

Requirements for using the package:

  1. The mapper file name needs to be consistent with the interface name and is case sensitive
  2. The mapper file and the dao interface need to be in the same directory


pageHelper is used for data paging

Need to import PageHelper dependency

<!--    PageHelper依赖-->

Need to be imported into the mybatis framework

        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>



xml files can be loaded into mybatis at one time

Requirements for using the package:

  1. The mapper file name needs to be consistent with the interface name and is case sensitive
  2. The mapper file and the dao interface need to be in the same directory


pageHelper is used for data paging

Need to import PageHelper dependency

<!--    PageHelper依赖-->

Need to be imported into the mybatis framework

        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>



mind Mapping

Insert picture description here