Mybatis

Introduction to the

The following is from the official documentation of Mybatis

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all of the JDBC code and the work of setting parameters and fetching result sets. MyBatis can configure and map primitive types, interfaces, and Java POJOs (Plain Old Java Objects) to records in the database via simple XML or annotations.

Mybatis official document

The following quotes are from Baidu Baike

MyBatis is an open source project of Apache called iBatis. In 2010, this project was migrated to Google Code by Apache Software Foundation and renamed as MyBatis. Migrated to Github in November 2013.

How do I get MyBatis

  • Maven repositories
  • GitHub

The persistence layer

So before we talk about persistence, what is persistence

  • Persistence is the process of converting program data into persistent and transient states
  • Memory has a property that it is lost when power is cut off. Unpersisted data in memory is called transient data
  • The process of converting this instantaneous data in memory into persistent data (stored in a permanent storage device, such as a disk or database) is called persistence

Now that we know what persistence is let’s talk about the persistence layer, okay

  • The persistence layer deals primarily with databases
  • The persistence layer is a relatively independent logical layer that focuses on the implementation of data persistence logic
  • The persistence layer improves operational efficiency by providing ORM mechanisms and encapsulating the necessary data manipulation methods, providing a method interface…….

Any enterprise-class Java Web application is inseparable from database operations, that is, data storage and acquisition. In particular, the efficient operation of a large amount of data is especially valued in the era of big data. Therefore, when using Java to develop enterprises and applications, how to improve the efficiency of data operation has become one of the factors that need to be considered in development. And the persistence layer framework, that is, came into being. In general, Java developers need to write a lot of repetitive code and embed related SQL statements to interact with the database without using a specific persistence layer framework (mostly basic data manipulation business, such as SINGLE-data CRUD SQL code, and JDBC-related code). With the use of a specific persistence layer framework, the amount of code for database connections and interactions is significantly reduced. One of the more important reasons is that the persistence layer framework has completed the transformation from “object-oriented” to “relational”. This makes it possible to manipulate the corresponding data in the database by directly manipulating Java objects.

The above quote is from the article

This kind of data persistence operation can also be done using JDBC in the early years, but it is a bit cumbersome so in order to simplify (lazy) development, Mybatis framework came into being

Some features of Mybatis

  • Easy to learn, small and simple in itself. Without any third party dependence, the simplest installation as long as two JAR files + configuration several SQL mapping files easy to learn, easy to use, through the documentation and source code, can be more fully grasp its design ideas and implementation.
  • Flexible, MyBatis does not impose any impact on the existing design of the application or database. SQL is written in XML for unified management and optimization. All requirements for operating a database can be met through SQL statements.
  • Uncoupling SQL from program code. By providing the DAO layer, the business logic and data access logic are separated, which makes the system design clearer, easier to maintain, and easier to unit test. Separation of SQL and code improves maintainability.
  • Provides mapping labels to support orM field relational mapping of objects to databases
  • Provides object-relational mapping labels to support object-relational maintenance
  • Provides XML tags to support writing dynamic SQL.

Implement a Mybatis program

Set up the environment

  • Create database (depending on preference, build database build table insert data can be.

  • Create a Maven project

  • Import the required dependencies in POM.xml

    •     <dependencies>
              <! Import mybatis dependencies -->
              <dependency>
                  <groupId>org.mybatis</groupId>
                  <artifactId>mybatis</artifactId>
                  <version>3.5.2</version>
              </dependency>
              <! MySQL > import MySQL driver
              <dependency>
                  <groupId>mysql</groupId>
                  <artifactId>mysql-connector-java</artifactId>
                  <version>8.0.21</version>
              </dependency>
              <! -- Import junit for testing -->
              <dependency>
                  <groupId>junit</groupId>
                  <artifactId>junit</artifactId>
                  <version>4.13</version>
              </dependency>
          </dependencies>
      Copy the code
    • In the Maven sidebar, make sure your dependencies are imported successfully

  • Copy the mybatis core configuration file from the official website. Copy it here


      
<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<! -- Core Configuration file -->
<configuration>
    <! -- environment, you can define multiple sets of environment -->
    <environments default="development">
        <! -- Use environment -->
        <environment id="development">
            <! -- Default JDBC transaction management -->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <! -- User login information, it is not recommended to directly write the login information here -->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <! Mapper configuration file -->
      <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>
Copy the code

At this point our environment is ready

Build the sqlSessionFactory from XML

Each MyBatis application is built around an instance of the SqlSessionFactory. An instance of SqlSessionFactory can be obtained from SqlSessionFactoryBuilder. SqlSessionFactoryBuilder, on the other hand, can build an SqlSessionFactory instance from an XML Configuration file or a pre-configured Configuration instance.

Building an instance of SqlSessionFactory from an XML file is straightforward, and it is recommended to use a resource file under the classpath for configuration. But you can also use an arbitrary instance of an InputStream, such as an InputStream constructed from a file path string or a file:// URL. MyBatis includes a utility class called Resources, which contains utility methods that make it easier to load resource files from the classpath or elsewhere.

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
Copy the code

Do not use XML to configure the sqlSessionFactory(Not recommended)

If you prefer to create configurations directly from Java code rather than XML files, or want to create your own configuration builder, MyBatis also provides complete configuration classes that provide all configuration items equivalent to XML files.

DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
Copy the code

Note that in this example, Configuration adds a Mapper class. Mapper classes are Java classes that contain SQL mapping annotations to avoid dependency on XML files. However, due to the limitations of Java annotations and the complexity of some MyBatis mappings, XML configuration is still required to use most advanced mappings (e.g., nested union mappings). For this reason, if there is an XML configuration file with the same name, MyBatis automatically finds and loads it (in this case, blogmapper.xml is loaded based on the classpath and the blogmapper.class class name). Details will be discussed later.

The role of SqlSessionFactory

Now that we have SqlSessionFactory, as the name implies, we can get an instance of SqlSession from it. SqlSession provides all the methods needed to execute SQL commands in the database. You can use the SqlSession instance to execute the mapped SQL statement directly. Such as:

try (SqlSession session = sqlSessionFactory.openSession()) {
  Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog".101);
}
Copy the code

Write the MyBatis utility class

// the main purpose of this utility class is to let other classes getSqlSession objects by calling its getSqlSession method
public class MybatisUtils {
    // Increase the scope of the SqlSessionFactory object so that getSqlSession can call its methods directly
    private static SqlSessionFactory sqlSessionFactory;

    // put it in a static code block and load it when initialized
    static {
        try {
            //2. Load the configuration file
            String resource = "mybatis-config.xml";
            // read the core configuration file and return the inputStream object
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //4. Create SqlSessionFactory from inputStream
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch(IOException e) { e.printStackTrace(); }}// write a method that can get an instance of sqlSession
    public static SqlSession getSqlSession(a){
        // The openSession method returns an instance of SqlSession
        returnsqlSessionFactory.openSession(); }}Copy the code

Mybatis initialization process

In order to avoid confusion about the above tool class, I will briefly introduce the initialization process of Mybatis, of course, this has involved the source code need not go into depth, to understand.

If you're more confused than you already are, this initial introduction is counterproductive and can be read selectively.

  • Once MyBatis is running, the core configuration file must be loaded through Resources to get an input stream.

  • The input stream is passed as a parameter to the buid method of the SqlSessionFactoryBuilder, which is used to create the SqlSessionFactory object.

  • Before creating SqlSessionFactory objects, the information such as the SqlSessionFactoryBuilder is according to the input stream, first create a XmlConfigBuilder object,

  • The XmlConfigBuilder object, which can be called a parser, parses the core Configuration file and encapsulates the results in the Configuration object.

  • SqlSessionFactoryBuider creates a DefaultSqlSessionFactory object based on the Configuration object

  • After the factory object is successfully created, the programmer can create the SqlSession object by calling the openSession method.

  • SqlSession object is the core object in MyBatis, all database operations are based on this object.

SqlSession as the core API of Mybatis, it is mainly used to execute commands, obtain mappings and manage transactions. Receives the Statement Id and parameters provided by the developer and returns the result of the action.

How does the openSession method of SqlSessionFactory create an SqlSession object

  1. Get the Environment data source from the Configuration class.
  2. Get the TransactionFactory and DataSource from the DataSource and create a Transaction connection management object.
  3. Create Executor (SqlSession is just the facade of all the operations, the real work is Executor, which encapsulates all the details of the underlying JDBC operations). MyBatis uses SimpleExecutor by default
  4. The DefaultSqlSession object is then created based on the Executor. The SqlSession object is successfully created.
  5. Programmers can call the corresponding method based on SqlSession to operate the database

Let’s address the database login information in the MyBatis configuration file

  • Start by creating a db.properties file in the Resources directory
  • In the db.properties file, write down your driver, URL, USERNAME, and password.
driver=com.mysql.jdbc.Driver
url=JDBC: mysql: / / localhost: 3306 / database name? serverTimezone=GMT%2B8&useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=The user name
password=password
ServerTimezone =GMT%2B8 serverTimezone=GMT%2B8
Copy the code
  • Introduce db.properties into the MyBatis configuration file

    • <! It must be placed at the top of the < Configuration > TAB, otherwise an exception will occur -->
      <properties resource="db.properties"/>
      Copy the code
  • Configure login information in db.properties in mybatis configuration file

  • At the value of the property tag, reference the configuration information in the db.properties file using the $symbol and a pair of curly braces, as follows. This is the default copy from the official website, no need to change

    <dataSource type="POOLED">
        <! -- User login information -->
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    </dataSource>
    Copy the code

Writing entity classes

package com.molu.pojo;

// Write the entity class
public class User {
    private int id;
    private String name;
    private String pwd;

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public User(a) {}

    public int getId(a) { returnid; }public void setId(int id) { this.id = id; }public String getName(a) { returnname; }public void setName(String name) { this.name = name; }public String getPwd(a) { returnpwd; }public void setPwd(String pwd) { this.pwd = pwd; }@Override
    public String toString(a) {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\' ' +
                ", pwd='" + pwd + '\' ' +
                '} '; }}Copy the code

From the fields in the database we write an entity class that generates some methods that need to be used, but you can also use Lombok to be lazy, it’s all the same

Compile Mapper interface and configuration file

Simply write a Mapper interface

public interface UserMapper {
    // Simply write a query method in mapper interface
    List<User> getUserList(a);
}
Copy the code

After writing the interface, we should write an interface implementation class that inherits the interface and overwrites its methods. But in Mybatis, instead of writing the implementation class of the interface, we write a Mapper configuration file.

Recourse You can write the Mapper configuration files under the recourse directory or under your own mapper package together with the Mapper interface.

In the latter case, there is a problem with Maven static resource filtering. You need to copy the following configuration to your pom.xml to prevent this problem

Static resource filtering is abnormal, you can try to put this configuration into POM.xml

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
Copy the code

Let’s start writing the mapper.xml configuration file

  • Start by copying the mapper. XML header and some examples from the official website


      
<! DOCTYPEmapper
  PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<! --> < span style = "max-width: 100%;
<mapper namespace="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
Copy the code
  • Let’s start with these examples

    • First, the Mapper tag has a namespace attribute, which is used to bind the Mapper interface

    • We can also write specific database operations in mapper tags, using the following tags

    • Start with the SELECT tag, which has the ID and resultType attributes that can be configured

      • The ID attribute is used to specify methods in the interface
      • The resultType attribute is used to specify the return value type of the method
    • Write specific SQL in the body of the SELECT tag

  • With these examples in mind, we started writing our own Mapper configuration file


      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<! --> < span style = "max-width: 100%;

<! -- Namespace attribute, binding mapper interface -->
<mapper namespace="com.molu.mapper.UserMapper">
    <! --id bound to methods in our interface -->
    <! --resultType writes the returned type to the fully qualified name. Our interface query method generic is User, we will write the fully qualified name of User -->
    <select id="getUserList" resultType="com.molu.pojo.User">
    select * from mybatis.user
  </select>
</mapper>
Copy the code

After the mapper configuration file is written, we need to bind it in the core configuration file of Mybatis

I wrote mapper. XML in the Resources directory, along with the Mybatis configuration file, so binding is also easy.

    <mappers>
        <mapper resource="mapper.xml"/>
    </mappers>
Copy the code

The test class

public class MapperTest {
	@Test
    public void test(a){
        SqlSession instance (); sqlSession instance ()
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        // We get the mapper interface object from sqlSession's getMapper method
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        // Call methods in the interface through the interface object
        List<User> userList = mapper.getUserList();
        // Iterate over the returned array
        for (User user : userList) {
            System.out.println(user);
        }
        // Close the connectionsqlSession.close(); }}Copy the code

The test class is a little bit confusing, so LET me explain how it works

  • There should be no confusion as we get sqlSession directly from our written utility classes

    • As mentioned above, this sqlSession is the core API of Mybatis, we can use it to execute SQL.

    • SQL resides in the mapper.xml configuration file

    • SqlSession contains a getMapper method that retrieves the object of the interface

    • An object with an interface can use a method in the interface, which performs a dynamic proxy operation when called

    • Using this dynamic proxy, we can take the SQL from mapper.xml and execute it.

    • After executing the SQL, the result of the query is encapsulated in the returned userList. We just need to pay attention to the returned value type and iterate over it to get the data in our database.

Instead of using getMapper to get the interface object, there’s another way to do it.

public class MapperTest {

    @Test
    public void test(a){
        SqlSession instance (); sqlSession instance ()
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        // The second way is to write our interface classes and methods to sqlSession methods and force the returned Object to the desired type
        List<User> userList = sqlSession.selectList("com.molu.mapper.UserMapper.getUserList");
        // Iterate over the returned array
        for (User user : userList) {
            System.out.println(user);
        }
        // Close the connectionsqlSession.close(); }}Copy the code

Of course, this method is not recommended and is a bit outdated.

GetMapper is also recommended in the official website, so understand this method

That’s it for MyBatis’ basic understanding and simple implementation. The MyBatis article will be updated one after another. Thank you for reaching one red item (◝).


The original address

Painters home page