MyBatis from recognition to environmental construction

MyBatis from recognition to environmental construction

What is the original jdbc like?

Briefly review the process of using JDBC: ① introduce relevant database driven Jar package; ② create a database connection class

This class includes: database driven loading, database connection configuration, connection object acquisition, release and close, as well as specific SQL and its execution statement. The following is a

The following code is the most original way of JDBC. Without any optimization and encapsulation, the function is to query all records in the student table

package cn.ideal.jdbc;

import cn.ideal.domain.Student;

import java.sql.*;

public class JdbcDemo {
    public static void main(String[] args) {

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            //Registration driven
            //Get the connection object to the database
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "root99");
            //Defining sql statements
            String sql = "SELECT * FROM student";
            //Get the object statement of executing sql statement
            statement = connection.createStatement();
            //Execute sql statement to get result set
            resultSet = statement.executeQuery(sql);

            //Traverse the result set obtained
            while ( {
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                Double score = resultSet.getDouble(3);

                Student student = new Student();


        } catch (ClassNotFoundException e) {
        } catch (SQLException e) {
        } finally {
            //Release resources, first release after calling.
            if (resultSet != null) {
                try {
                } catch (SQLException e) {

            if (statement != null) {
                try {
                } catch (SQLException e) {

            if (connection != null) {
                try {
                } catch (SQLException e) {

Through this code, we can analyze:

  • ① In the code, the database driver name, link address, account password, etc. are all written into the program, that is to say, when you need to modify some values, you must modify the source code, which is what we call "hard coding"
    • For example: if we change the database Eg: MySQL - > Oracle, or change the server, so the address has changed, or the database password has been modified, we need to go back to the source code to modify, recompile, package and go online
  • ② Database connection needs frequent creation and release, system resource waste, and impact performance (solved by database connection pool technology)

This code uses the preparedStatement preprocessing object to replace its parent class Statement object, which is what we usually choose when we only consider the original JDBC case, so what's the problem with it?

//Define sql
String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
//Get the object to execute sql
preparedStatement = connection.prepareStatement(sql);
//Assign value to
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);

//Execution query
resultSet = preparedStatement.executeQuery();
  • ③ When using preparedStatement to set placeholder statement and pass parameters to it, it is "hard coded" because the where condition of sql statement may change. If it is necessary to modify sql, modify the source code

There is another situation:

//Traverse the result set obtained
while ( {
	int id = resultSet.getInt("id");
	String name = resultSet.getString("name");
	Double score = resultSet.getDouble("score");

	Student student = new Student();

  • ④ If we use getInt and other methods when traversing the result set in the ResultSet, the parameter is the field name. When the corresponding table field of the database changes, the source code needs to be modified again

Before, we had some convenience in our development. We may have used Spring's JdbcTemplate or Apache's DBUtils, which are simple packages of JDBC. They can only be counted as tool classes, not as a complete framework. But Mybatis is a framework that can solve these problems

MyBatis overview

MyBatis is an excellent persistence framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manual setting of parameters and getting result sets. MyBatis can use simple XML or annotation to configure and map native information, and map interface and Java POJOs(Plain Ordinary Java Object) to records in database -- Baidu Encyclopedia

1. MyBatis can configure sql statements in XML, which solves the "hard coding" problem of sql statements written in Java classes

2. Through the input parameter mapping mechanism, the parameters can be flexibly configured to solve the problem of manual configuration in Java classes

3. Through the output mapping mechanism, the retrieval of result sets is automatically mapped to corresponding Java objects, avoiding the manual retrieval of result sets in JDBC

4. This mapping mechanism actually uses the idea of ORM

  • ORM (Object Relational Mapping) object relational mapping
  • Simple understanding: database table corresponds to the attribute in entity class. We can operate entity class to operate database table

Environment configuration (IDEA) for MyBatis

(1) Create Maven project

Open IDEA and create a Maven project, as shown in the following figure

Modify the values of GroupId and ArtifactId

  • GroupID is the unique identifier of the project organization. The actual package structure corresponding to Java is the directory structure of Java in the main directory
    • Generally fill in the domain name in reverse order
  • ArtifactID is the unique identifier of the project. The name of the actual corresponding project is the name of the project root directory

Set its address

(2) Modify pom import MyBatis coordinates

Select jar package as the packaging method: < packaging > jar < / packaging >

Now we import the dependency of mybatis, mysql, log4j (log), junit (unit test)

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

    <!-- Packaging method -->

    <!-- Correspondence dependence -->


(3) Create entity class

package cn.ideal.domain;

import java.util.Date;

public class User implements Serializable {
    private Integer id;
    private String username;
    private Integer telephone;
    private Date birthday;
    private String gender;
    private String address;

	...To save length, omit its corresponding get set Methods, please supplement by yourself

    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", telephone=" + telephone +
                ", birthday=" + birthday +
                ", gender='" + gender + '\'' +
                ", address='" + address + '\'' +

(4) Create mapper interface

The meaning of mapper is the same as that of dao we learned before, but the name is different. It is OK to write the corresponding mapper as dao

package cn.ideal.mapper;

import cn.ideal.domain.User;
import java.util.List;

public interface UserMapper {
     * Query all user information
     * @return
    List<User> findAllUserInfo();

(5) Write database connection pool profile (primary profile)

Create a file named SqlMapConfig.xml under resources, which is our main configuration file

The configuration of database connection pool is an important point in the configuration environment

  • ① Because its configuration file is in xml format, we need to specify the version and encoding information of xml in the header
<?xml version="1.0" encoding="UTF-8"?>
  • ② In order to ensure that when MyBatis reads the xml file, every label pair in the configuration file and the parameter value configuration in the label pair meet the standards, DTD specification constraints are introduced
<!DOCTYPE configuration
        PUBLIC "-// Config 3.0//EN"

Next is the configuration body,

  • The default value in the < environments > < environments > tag must be the same as the id value in < environment > < / < environment >

  • < transactionmanager > < transactionmanager > configure transaction control type of Mybatis

  • < datasource > < / < datasource > configure database connection information

    • < property > < property > configure specific values
  • The location of the mapping configuration file is specified in the < mappers > < mappers > tag at the bottom, which means that our SQL related statements are in the specified configuration file, and here we specify its path

Detailed code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-// Config 3.0//EN"
<!-- mybatis Master profile -->
    <!-- Configuration environment, and spring After integration environments Configuration will be abolished -->
    <environments default="development">
        <environment id="development">
            <!-- Use JDBC transaction management -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- Database connection pool -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ideal_mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="=root99r"/>

    <!-- Specify the location of the mapping profile -->
        <mapper resource="cn.ideal.dao/UserMapper.xml"/>

(6) SQL mapping profile

In order to solve some shortcomings of native JDBC, in MyBatis, SQL statements will not appear directly in Java classes. It will put almost all SQL statements in the configuration file. It will load the configuration file and complete certain operations under appropriate circumstances

The first is still the version and encoding format of xml, and then the DTD constraint is introduced

Then write our specific configuration in the < mapper > < mapper > tab

  • The namespace attribute is to classify and manage the SQL, and separate the SQL that implements different businesses. Here, we take the value of it as the fully qualified class of the mapper interface before us
  • Special note: when creating a package, we create a three-level directory. When creating a directory for configuration files, we directly create cn.ideal.mapper as a first-level directory. We need to create one-level directory to ensure that it is also a three-level directory
  • Create a < Select > < Select > tag in the < mapper > < mapper > tag where the value of the attribute id is the method name of the mapper interface
    • parameterType, parameterMap, resultType, resultClass and resultMap respectively represent
    • Input parameter type, input parameter set, result type, result class, result set
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<mapper namespace="cn.ideal.mapper.UserMapper">
    <select id="findAllUserInfo" resultType="cn.ideal.domain.User">
        select * from  user

I'm finished with my brief understanding of Mybatis and the construction of the environment. The length of the article is divided into several parts. Thank you for your support


If there are any shortcomings or mistakes in the article, please leave a message and share your ideas. Thank you for your support!

If you can help, then pay attention to me! If you prefer the way of reading WeChat articles, you can pay attention to my public number.

We don't know each other here, but we are working hard for our dreams

A public figure that persists in pushing original development technology articles: ideal two days

Tags: Programming Mybatis SQL Database JDBC

Posted on Wed, 29 Jan 2020 00:52:16 -0800 by somedude