In-depth MyBatis: Introduction to JDBC and MyBatis

Recently, I was on paternity leave, and the time was relatively fragmented. I was going to read two books to enrich, one is "MyBatis in simple terms: technical principles and practice", and the other is "RabbitMQ combat: Efficient deployment of distributed message queues", in order to deepen memory and Understand, organize, expand and document.

The goal of reading a book is not to memorize all the details, but to understand what a technology can do as a whole, its features, basic modules, implementation principles, and common usage scenarios.

This article shares the first part of the MyBatis book. First, I recall the related concepts of JDBC, understand the most basic way to access the database provided by Java, and then introduce the basic features and core components of MyBatis. Finally, I will talk about the overall structure of the book and understand the follow-up The general content of the article.

JDBC related concepts

Java programs are connected to the database through JDBC, and the database is programmed through SQL. JDBC is a series of specifications proposed by SUN. It only defines the interface specifications. The specific implementation is implemented by each database manufacturer. It is a typical bridge mode. .

The bridge pattern is a structural design pattern. Its main feature is to separate the abstraction from the behavior implementation, and define the interface separately, which can maintain the independence of each part and deal with their functional expansion.

JDBC Specification

The so-called specification is to define a standard interface by itself, and make the following abstractions: use Connection to represent the connection to the database, use Statement to execute SQL, and use ResultSet to represent the result returned by SQL, which provides convenience for data. Statement can be created from Connection, and Statement executes query to get ResultSet.

The Connection, Statement, and ResultSet mentioned above should all be interfaces, and the specific implementation is provided by each database provider. With the specification, you can access multiple types of databases through a unified interface, and you can switch databases at will.

database driven

As mentioned above, the implementation of the interface is provided by various manufacturers, so the class names of the implementation classes will not be uniform. When creating a Connection object, the code will write a certain implementation class to death. When switching the database, the code needs to be modified, so that the Great. In order to solve this problem, the concept of Driver is abstracted.

Connection con=MySqlConnectionImpl("127.0.0.1",3306,"mi_user",userName,pwd);

Each database needs to implement the Driver interface. The database connection Connection can be obtained through the Driver and dynamically created through the reflection mechanism.

Class.forName("com.mysql.jdbc.Drier");

The same program may access different databases and manage the driver through the DriverManager. When the Driver is initialized, it needs to be registered in the DriverManager.

DriverManager provides a getConnection method for establishing a database Connection:

Connection con=DriverManager.getConnection("127.0.0.1",3306,"mi_user",userName,pwd);

If there are multiple database drivers, how does the DriverManager distinguish it? It needs to be specified in the database connection url. For example, mysql needs to add the jdbc:mysql prefix:

String url= "jdbc:mysql://127.0.0.1:3306/mi_user";
Connection con=DriverManager.getConnection(url,userName,pwd);
data source

The data source DataSource contains two parts: connection pool and connection pool management, which are customarily called connection pool. When the system is initialized, the database connection is stored in the memory as an object. When the database needs to be accessed, an established idle connection object is taken out from the connection pool.

Using a data source, obtain its DataSource object, and dynamically obtain a database connection through this object. In addition, the DataSource object can be registered with the name service (JNDI), and the DataSource object can be obtained through the name service without hard-coding the driver.

DriverManager is provided by JDBC1, and DataSource is a new function of JDBC2, which provides a better way to connect to data sources.

Comparing Hibernate and MyBatis

Through the above introduction, traditional JDBC programming brings us the function of connecting to the database, but its workload is relatively large. First connect, then process the underlying JDBC transaction, process data types, and capture and process possible exceptions. And close the resource properly.

In practical work, JDBC is rarely used for programming, and ORM model is proposed, which mainly solves the mutual mapping between database data and POJO objects.

Both Hibernate and Mybatis are ORM models. Hibernate provides a full-table mapping model with a high degree of encapsulation of JDBC. But Hibernate also has many disadvantages, listed as follows:

  • The inconvenience brought by full table mapping, such as the need to send all fields when updating;
  • Cannot assemble different SQL based on different conditions;
  • Poor support for multi-table associations and complex SQL queries, you need to write your own SQL, and after returning, you need to assemble the data into POJOs by yourself;
  • cannot effectively support stored procedures;
  • Although there is HQL, the performance is poor, and large Internet systems often need to optimize SQL, which Hibernate can't do.

In a large-scale Internet environment, flexibility, SQL optimization, and reducing data transmission are the most basic optimization methods. Hibernate cannot meet the requirements, and MyBatis provides you with a flexible and convenient way, which is a semi-automatic mapping framework.

MyBatis needs to provide POJO, SQL and mapping relationship manually, while Hibernate with full table mapping only needs to provide POJO and mapping relationship.

MyBatis can configure dynamic SQL, which can solve the problem that Hibernate's table name changes according to time, and different conditions are listed. It can optimize SQL, determine SQL mapping rules through configuration, and support stored procedures, which is more convenient for some complex SQL queries that require optimized performance.

core components

The core components mainly include the following:

  • SqlSessionFactoryBuilder: SqlSessionFactory will be generated based on configuration information or code;
  • SqlSessionFactory: rely on the factory to generate SqlSession;
  • SqlSession: It is an interface that can not only send SQL to execute and return results, but also obtain Mapper;
  • SQL Mapper: It is a newly designed component of MyBatis. It consists of a Java interface and an XML file. The corresponding SQL and mapping rules need to be given. It is responsible for sending SQL to execute and returning the result.
Build SqlSessionFactory

Every MyBatis application is centered on an instance of SqlSessionFactory, which is tasked with creating SqlSessions. SqlSession is similar to a JDBC Connection object.

There are two ways to create SqlSessionFactory: one is the way of XML configuration, the other is the way of code, it is recommended to use the way of XML configuration.

Define the mybatis-config.xml file as follows:

<? 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>
 <properties resource="application.properties">
 </properties>

 <!-- 定义别名 -->
 <typeAliases>
 <typeAlias alias="role" type="com.learn.chapter2.po.Role"/>
 </typeAliases>

 <!-- 定义数据库信息.默认使用development数据库构建环境 -->
 <environments default="development">
    <environment id="development">
    <!-- 采用jdbc事务管理 -->
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="${driver}"/>
            <property name="url" value="${url}"/>
            <property name="username" value="${username}"/>
            <property name="password" value="${password}"/>
        </dataSource>
    </environment>
 </environments>

 <!-- 定义映射器 -->
 <mappers>
 <mapper resource="com\learn\chapter2\mapper\roleMapper.xml"/>
 </mappers>
</configuration>

Create SqlSessionFactory

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

SqlSession is an interface class that plays the role of the facade, and the real work is the Executor interface. It needs to be ensured that it is properly closed every time it is used up.

SqlSession sqlSession=null;
try{
    sqlSession=sqlSessionFactory.openSession();
    //some code
    sqlSession.commit();
} catch(Exception ex){
    sqlSession.roolback();
} finally{
    if(sqlSession!=null){
        sqlSession.close();
    }
}
mapper

The mapper is composed of a Java interface and an XML file (or annotation), and the functions are as follows:

  • Define the parameter type
  • description cache
  • Describe the SQL statement
  • Define the mapping relationship between query results and POJOs

First, define the Java interface:

public interface RoleMapper{
    public Role getRole(Long id);
}

Then, define the mapping XML file, RoleMapper.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">

 <mapper namespace ="com.learn.chapter2.mapper.RoleMapper">
    <select id="getRole" paramterType="long" resultType="role" >
        select id,role_name as roleName , note from t_role where id=#{id}
    </select>
 </mapper>

The definition of POJO object Role is relatively simple, so it will not be listed. #{id} is the parameter of this SQL. The alias of the SQL column is consistent with the property name of the POJO, and the query result of this statement will be automatically mapped to the Role property, which is automatic mapping.

execute query

RoleMapper roleMapper=sqlSession.getMapper(RoleMapper.class);
Role role=roleMapper.getRole(1L);
String roleName=role.getRoleName();
component life cycle

In the entire life cycle of the MyBatis application, each database corresponds to only one SqlSessionFactory, which can implement a tool class and obtain the object in a singleton mode.

The life cycle of SqlSession is in the process of requesting the database to process transactions. It is a thread-unsafe object. Special care should be taken when multi-threading is involved. It survives the requests and operations of an application, and can execute multiple SQLs to ensure transaction consistency.

The role of Mapper is to send SQL and then return the required results, or execute SQL to modify the data in the database, so it should be within a SqlSession transaction method, just like the execution of an SQL statement in JDBC, its maximum scope is the same as that of SqlSession .

overall structure of the book

This book is divided into 3 parts, which successively introduce the basic application, principle and plug-in development and practical application of MyBatis.

Basic application

Mainly introduce how to use MyBatis efficiently:

  • MyBatis Features
  • Core Components and Their Lifecycles
  • MyBatis configuration
  • mapper
  • Dynamic SQL
MyBatis principle

In-depth source code to understand the internal operation principle of MyBatis and the development methods and skills of plug-ins:

  • Introduce the analysis and operation principle of MyBatis, and learn about the construction method of SqlSession and how the four major objects work
  • Introducing MyBatis plugins
Practical application

Mainly explain some practical scenarios of MyBatis:

  • Introduce MyBatis-Spring and explain how to integrate MyBatis applications in Spring projects
  • Introduce the practical scenarios of MyBatis, select some typical scenarios, and analyze some errors and performance losses that developers need to avoid in each scenario.

The next part will introduce the relevant configuration of MyBatis, better configure MyBatis to apply to different business scenarios, and the extensions provided to us.

love story

Guess you like

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