The first program of Mybatis written by Mybatis

Written in the front: this note is part of the concept that I organized by following the madness teacher's video self-study. Please refer to Baidu Encyclopedia and official documents

System environment:

  • jdk 12
  • mysql 8.0.17
  • maven 3.6.2
  • IDEA

What is MyBatis

  • MyBatis an excellent persistence framework
  • MyBatis avoids almost all the JDBC code and manual setting of parameters and getting the result set
  • MyBatis can use simple XML or annotation to configure and map native information, and map interface and Java entity class (Plain Old Java Objects, common Java objects) to records in database.
  • Official documents of Mybatis:
  • GitHub :

What is persistence

  • Persistence is a mechanism to transform program data between persistent state and transient state
  • That is, to save data (such as objects in memory) to a storage device (such as disk) that can be permanently saved. The main application of persistence is to store objects in memory in database, disk file, XML data file and so on.
  • JDBC is a persistence mechanism. File IO is also a persistence mechanism.
  • Store the contents of the memory in the hard disk for permanent storage (compared with the hard disk, the memory is lost when the power is off)

What is persistence layer

  • Code block to complete persistence work. --- > Dao layer [DAO (Data Access Object) data access object]
  • In most cases, especially in enterprise applications, data persistence often means that the data in memory is stored on disk to be solidified, and the implementation process of persistence is mostly completed through various relational databases.
  • But here is a word that needs special emphasis, that is, the so-called "layer". For application systems, data persistence is an essential part. That is to say, our system already has the concept of "persistence layer" naturally? It may be, but it may not be. The reason why we need to develop a concept of "persistence layer" instead of "persistence module" and "persistence unit" means that there should be a relatively independent logic layer in our system architecture, focusing on the implementation of data persistence logic
  • Compared with other parts of the system, this level should have a clear and strict logical boundary. [to put it bluntly, it is used to operate the existence of database! ]

Why do we need MyBatis

  • Replace the JDBC operation: Mybatis is to help the program ape store data in the database and get data from the database
  • Avoid the phenomenon of repeated wheel building: traditional jdbc operation, there are many repeated code blocks. For example: encapsulation when data is taken out, establishment and connection of database, 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
  • In the whole system development process, Mybatis is not a must, but with the help of Mybatis, we can make our project development easier.

Benefits of MyBatis

  1. Simple and easy to learn: small and simple, no third-party dependence
  2. Flexibility: no impact on the existing design of the application or database. sql is written in xml for unified management and optimization. Through sql statement, all the requirements of database operation can be satisfied.
  3. Decouple sql and program code: separate business logic and data access logic by providing DAO layer to make the system design clearer, easier to maintain and easier to unit test. The separation of sql and code improves maintainability.
  4. Provide xml tags

MyBatis first program

  1. Build database
    CREATE DATABASE `mybatis`;
    USE `mybatis`;
    CREATE TABLE `user` (
      `id` int(20) NOT NULL,
      `name` varchar(30) DEFAULT NULL,
      `password` varchar(30) DEFAULT NULL,
      PRIMARY KEY (`id`)
    INSERT INTO `user`(`id`,`name`,`password`) VALUES(1,'SKYID','123456'),(2,'Cai Xu Kong','123456');
  1. Import related Jar packages of Mybatis, Mysql and Junit through maven
            <!-- mysql drive-->
            <!-- mybatis-->
            <!-- junit-->
  1. Write MyBatis core configuration file - mybatis-config.xml
    <?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/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
                    <property name="username" value="root"/>
                    <property name="password" value="12345678"/>
            <mapper resource="com/sky/dao/UserMapper.xml"/>

property corresponds to mysql jar package, mysql URL address, mysql user name and password respectively

  1. Write Mybatis tool class according to official documents
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
        static {
            try {
                // Get SqlSessionFactory object with mybatis
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
        // Get sqlsession sqlsession through SqlSessionFactory. Sqlsession contains all methods of sql operation for database
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
  1. Create POJO entity class

    // Entity class
    public class User {
        private int id;
        private String name;
        private String password;
    //No reference method
        public User() {
        //Have ginseng
        public User(int id, String name, String password) {
   = id;
   = name;
            this.password = password;
        // get set method
        public int getId() {
            return id;
        public void setId(int id) {
   = id;
        public String getName() {
            return name;
        public void setName(String name) {
   = name;
        public String getPassword() {
            return password;
        public void setPassword(String password) {
            this.password = password;
        // toString
        public String toString() {
            return "User{"  
                    "id="   id  
                    ", name='"   name   '\''  
                    ", password='"   password   '\''  
  1. Write Mapper interface file (UserMapper)

    import java.util.List;
    public interface UserMapper {
        public List<User> getUserList();
  1. Write Mapper's xml file (UserMapper.xml)
    The interface file location of Mapper corresponding to namespace
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-// Mapper 3.0//EN"
    <!-- namespace Binding corresponding Mapper/DAO Interface-->
    <mapper namespace="">
        <select id="getUserList" resultType="">
            select * from mybatis.User
  1. Write test Junit unit tests
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    import java.util.List;
    public class UserMapperTest {
        public void selectUser() {
            SqlSession session = MybatisUtils.getSqlSession();
            //Method 1:
            //List<User> users = session.selectList("com.kuang.mapper.UserMapper.selectUser");
            //Method two:
            UserMapper mapper = session.getMapper(UserMapper.class);
            List<User> users = mapper.getUserList();
            for (User user: users){
  1. Run and test

Project structure

|-- mybatis-01
        |-- mybatis-01.iml
        |-- pom.xml
        |-- src
        |   |-- main
        |   |   |-- java
        |   |   |   |-- com
        |   |   |       |-- sky
        |   |   |           |-- dao
        |   |   |           |   |-- 
        |   |   |           |   |-- UserMapper.xml 
        |   |   |           |-- pojo
        |   |   |           |   |--
        |   |   |           |-- utils
        |   |   |               |--
        |   |   |-- resources
        |   |       |-- mybatis-config.xml
        |   |-- test
        |       |-- java
        |           |-- com
        |               |-- sky
        |                   |-- dao
        |                       |--

Common problem

Cannot find Mapper.xml

This problem is generally caused by the fact that the. XML file is not placed under resources. Therefore, we can configure it in born.xml


Prompt the jdk version does not match

It is also a maven configuration problem. Check whether the environment configuration under born.xml is consistent with the native jdk version

                <!-- <version>3.7</version> Default to the latest-->

This article is based on the platform of blog one article multiple sending OpenWrite Release!

Published 20 original articles, won praise 6, visited 2245
Private letter follow

Keywords: Mybatis xml Java Database

Added by Simply Me on Sun, 19 Jan 2020 09:14:16 +0200