Introduction and environment construction of MyBatis

Introduction to MyBatis

1, MyBatis history

The MyBatis framework encapsulates JDBC for connecting to the database, but it is faster and more efficient than the original JDBC!

MyBatis was originally an open source project ibatis of Apache. In June 2010, the project was migrated from Apache Software Foundation to Google Code. With the development team switching to Google Code, ibatis3 X was officially renamed MyBatis.

The code was migrated to Github in November 2013. iBatis comes from the combination of "internet" and "abatis". It is a persistence layer framework based on Java. The persistence layer framework provided by iBatis includes SQL Maps and Data Access Objects (DAO).

2, MyBatis features

(1) MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping

Customized SQL means that in MyBatis, all SQL statements need to be written by ourselves, unlike Hibernate framework, which can be generated automatically.

(2) MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets

(3) MyBatis can use simple XML or annotations for configuration and original mapping, and map the interface and Java POJO (Plain Old Java Objects) into records in the database (there is no need to write implementation classes!)

(4) MyBatis is a semi-automatic ORM (Object Relation Mapping) framework

3, Download of MyBatis

MyBatis download address:

4, MyBatis Silicon Valley video address (2022 complete!!!)

The content of this blog is based on the video of Shang Silicon Valley. The address of the video is ↓. You need to get it yourself. It is completely free. Please leave a message if the link expires. You can also search the "Shang Silicon Valley" official account on wechat and download it yourself!

Extraction code: 7j6a
--Sharing from Baidu online disk super member V3

5, Similarities and differences with other persistence layer frameworks


  • SQL is mixed in Java code with high coupling, resulting in hard coding internal injury
  • Maintenance is not easy, and SQL changes in actual development requirements, and frequent modifications are common
  • Long code and low development efficiency

Hibernate and JPA

  • Simple operation and high development efficiency
  • The long, difficult and complex SQL in the program needs to bypass the framework
  • Internal automatic production SQL is not easy to do special optimization
  • Based on the fully automatic framework of full mapping, it is difficult to partially map POJO s with a large number of fields.
  • Too many reflection operations lead to database performance degradation.


  • Lightweight performance
  • SQL and Java coding are separated, and the functional boundary is clear. Java code focuses on business and SQL statement focuses on data
  • The development efficiency is slightly lower than that of HIbernate, but it is completely acceptable

MyBatis environment construction

Project skeleton

Note: the Product entity class under pojo package is omitted, and the database table is given. Readers can create it by themselves!  

Database table data


1, Create Maven

Do not use idea's default Maven address! Use your own Maven warehouse.

2, POM XML file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""


        <!-- mybatis Framed jar package-->

        <!-- mysql-java of jar package -->

        <!-- test jar package -->

3, Create a core configuration file for MyBatis

The core configuration file of MyBatis is conventionally named MyBatis config XML, but this is only a suggestion, not a mandatory requirement!

After integrating spring, this configuration file can be omitted! (because it can be written in the spring configuration file)

The core configuration file is mainly used to configure the environment connecting to the database and the global configuration information of MyBatis

There are two things in general:

  1. Setting the environment of the database
  2. Import mapping profile


<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration
        PUBLIC "-// Config 3.0//EN" "">

    <!-- 1.Setting the environment for connecting to the database -->
    <environments default="development">
        <!-- Specific environment -->
        <environment id="development">
            <!-- Transaction manager -->
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/demo?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="888888"/>

    <!-- 2.Configuration mapping file -->
        <mapper resource="mappers/ProductMapper.xml"/>


4, Create mapper interface

ProductMapper interface

package com.Harmony.dao;

import java.util.List;

public interface ProductMapper {

     * Add item
    int insertProduct();


5, Create a mapping file for MyBatis

ORM (Object Relationship Mapping) Object Relationship Mapping.

  • Object: Java entity class object
  • Relationships: relational databases
  • Mapping: the corresponding relationship between the two
Java conceptsDatabase concept
attributeField / column
objectRecord / line

1. Naming rules for mapping files:

Class name of the entity class corresponding to the table + mapper xml

For example: table t_user, the mapped entity class is user, and the corresponding mapping file is usermapper xml

Therefore, a mapping file corresponds to an entity class and the operation of a table

To access the data in the My SQL file, and to access the data in the Batis table

MyBatis mapping files are stored in the Src / main / resources / maps directory

2. MyBatis can operate data facing the interface, and the two must be consistent:

a> The full class name of the mapper interface is consistent with the namespace of the mapping file

b> The method name of the method in the mapper interface is consistent with the id attribute of the SQL tag written in the mapping file


<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN" "">
<mapper namespace="com.Harmony.dao.ProductMapper">

    <insert id="insertProduct">
        insert into product values(105,"computer",123.23,8)


6, Write test classes and test through juit

package com.Harmony.test;

import com.Harmony.dao.ProductMapper;
import com.Harmony.pojo.Product;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.util.List;

public class MyBatisTest {

    public void testInsertMyBatis() throws IOException {

        //Load core profile
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");

        //Get SqlSessionFactoryBuilder object
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        //Create a factory class SqlSessionFactory through the byte input stream corresponding to the core configuration file to produce SqlSession objects
        SqlSessionFactory sqlSessionFactory =;

        SqlSession sqlSession = sqlSessionFactory.openSession();

        ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);

        int result = mapper.insertProduct();

        //Transaction to commit



Tags: Java Mybatis SSM programming language

Posted by coolbeansdude51 on Thu, 05 May 2022 10:17:52 +0300