Self-study Mybatis series (1) - the basic composition of MyBatis

JAVA Persistence Layer Framework - MyBatis Learning


Written in the front: I am very grateful for the book "Mybatis Technical Principles and Practical Combat". Most of the places are in the book. I hope I can write more about my own understanding in the following articles. And most importantly! I feel so ashamed (shy face) every time I knock on the book without thinking. Be sure to pay attention to these issues later. Finally, I would like to thank the friends who liked, commented and corrected, you are the roar! !

Traditional JDBC and now Mybatis

Steps to use JDBC to access the database:
1. Use JDBC programming to connect to the database, register the driver and database information.
2. Operate the Connection and open the Statement object
3. Execute SQL through the Statement, and return the result to the Result object
4. Use the Result to read the data and convert it into a specific entity class object through the code It can be
seen that traditional JDBC has many drawbacks, which can be summed up as workload Large, it takes a lot of energy to deal with the complex.
The ORM model appeared later, and the significance of ORM is that a mapping model is established between database data and entity classes. For example, Hibernate is a very popular ORM model. Since Hibernate encapsulates JDBC to a high degree, we do not need to write SQL language, but only need to use HQL language.
The article on this topic is about MyBatis, and the author has not been exposed to Hibernate programming, so he will not write code.

Since Hibernate is not lightweight enough, Mybatis appeared, which is flexible, SQL-optimized, and reduces data transfer. It is in line with the mainstream programming style of today's era

Getting Started with Mybatis

For the time being, I don't care about the history of Mybaits. I'm going straight to learn how it works and how it works.
The package of MyBatis can be downloaded on the official website, and you can use the official document to paste the code.

The basic composition of MyBatis

  • SqlSessionFactoryBuilder: Constructor, which generates SqlSessionFactory based on configuration information and code.
  • SqlSessionFactory: Factory interface, relying on the factory to generate SqlSession.
  • SqlSession: A session is an interface that can both send SQL to execute the result and obtain Mapper.
  • SQL Mapper: It is composed of a Java interface and an XML file. It needs to give the corresponding SQL and mapping rules. It sends the SQL to execute and returns the result.

SqlSessionFactory is the core of MyBatis , and its instance can be obtained through SqlSessionFactoryBuilder. And the task of SqlSessionFactory is to create SqlSession.
There are two ways to create a SqlSessionFactory: 1. Configure it through an xml file. 2. Use code directly.
The author likes a simpler way and only uses the xml file configuration method!

Build SQLSessionFactory using xml

Here is a simple example:
DataSource: Get the data source of the database connection instance.
TransactionManager: The transaction manager that determines the scope and control of the transaction.
SQL Mapper: mapper
mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"    ?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
 <configuration>
    <!--定义数据库信息-->
    <environments default="development">
        <environment id="development">
            <!--采用jdbc事务管理-->
            <transactionManager type="JDBC" />
            <!--配置数据库链接信息-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Drive"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="数据库用户名"/>
                <property name="password" value="数据库密码"/>                   </dataSource>
        </environment>
    </environments>
    <!--定义映射器-->
    <mappers>
        <mapper resource="你的xxxMapper.xml文件">
    </mappers>
 </configuration>

Please explain, here I typed according to the book, please correct me if there are any mistakes, thank you very much.
An xml file is introduced here, which contains the information inside the mapper. Mybatis will parse it, generating a mapper.

Below is the code to create the SqlSessionFactory

    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = null;
    sqkSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

Here, SqlSessionFactoryBuilder is used to read the content of the xml file to create the SqlSessionFactory object.

Create SqlSession

The SqlSession interface has two uses:
- Get the mapper, send it to the database, execute the operation, and return the result
- You can operate the SQL configured in Xml through methods such as update, insert, select, delete, etc., and also support transactions, that is, through commit () commits the transaction and rollback() rolls back the transaction.

mapper

The role of the mapper:
1. Define the parameter type
2. Describe the cache
3. Describe the SQL statement
4. Define the relationship between the query result and the entity class

I still like to use xml to implement, because it is convenient, yes, for programming, it is the best thing to be able to use a simple way XD. And I'm not going to be entangled in the code now. I was going to introduce it briefly first, but I ended up writing a lot, and typing the code on the book by hand is very tiring!

The life cycle

SqlSessionFactoryBuilder

The function is the constructor. After we build the SqlSessionFactory we need, the SqlSessionFactoryBuilder has completed its mission and can be honored, so its cycle exists in the method part.

SqlSessionFactory

The role is to create SqlSession The last sentence in the book is very good: SqlSessionFactory has the sole responsibility, that is, to create SqlSession. Then we know that every time the program needs to access the database, we have to create a SqlSession, and to create it, we need our SqlSessionFactory, which means that it should exist in the entire life cycle of the application. Exactly, after understanding it, you can infer: OK! Then use the singleton pattern! Good Job!

SqlSession

SqlSession is a session, we have to close it every time we create it and use it. If we don't close it, the connection resources of our database will be consumed soon. The system is directly paralyzed, Game Over. So we turn it off in the finally block. It exists in an application's requests and operations.

Mapper

The function is to send SQL and return the result, so it should be within a corresponding SqlSession transaction method, and its maximum scope is the same as that of SqlSession. Try to use them in a method of a SqlSession transaction and discard them

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324732139&siteId=291194637