(1) MyBatis from entry to soil-introduction

This is the first in the MyBatis series. About 13 articles will be used to explain MyBatis. Those who like this series are welcome to pay attention to the public account [Java Tsukuba] for the latest articles. So not much nonsense, let's get started!

The era without MyBatis

Speaking of MyBatis, it must start from the time when MyBatis did not exist. At that time, most of our database development was done using jdbc. But the JDBC operation database is really big to use. Very tedious and boring, it is prone to problems and errors. The specific situation is as follows:

JDBC era

The process of connecting to the database:
  • Load the driver
  • Get connection
  • Splicing sql
  • Execute sql
  • Get results
  • Analysis result
  • Close the database

The above operations are all processes that we must go through when we use jdbc to connect to the database. It can be seen that the steps are very cumbersome. The key is that many of these steps are not what our programmers really care about. What we programmers really care about is splicing SQL, executing SQL, and parsing the results.

But based on the JDBC framework, other operations have to be written and operated, which makes us very laborious and redundant in code writing, which is not particularly friendly to programmers.

JDBC disadvantages

As mentioned above, JDBC has some fatal shortcomings. Generally speaking, there are the following aspects:

  • Too much duplicate code
  • Each operation takes too much time
  • Troublesome debugging and maintenance
  • There is no standard for dynamic sql and it is difficult to maintain

It is precisely because JDBC has some fatal shortcomings that we use other frameworks to complete the interaction with the database, such as Hibernate and MyBatis are the better representatives.

Hibernate

Before introducing hibernate, let's first understand what is ORM?

SNAKE

ORM: Object-relational mapping. Simply put, it is to establish a mapping relationship between the tables in the database and the objects in Java, which allows us to manipulate objects to indirectly manipulate the database.

The best framework for ORM is hibernate, which allows you to indirectly manipulate the database through java objects. It is easier for developers to get started, and the interaction process between the underlying jdbc and db is hidden. It is compatible with different databases for programmers, but it is insensitive to programmers. Just need to operate the database like an object

It is even so convenient that even if you don't know SQL, you can use it to operate the database. It can be said to be very friendly, especially for young partners who are new to the workplace and have poor work experience.

advantage

In summary, the advantages are:

  • Simplify the entire jdbc operation process
  • Need to manipulate the object, do not need to care about sql, hibernate can help us automatically generate the required sql
  • Code portability is better. The operation of db through hibernate is carried out through the operation object. If we need to switch the type of db, hibernate will automatically adapt, and there is no need to make any business code adjustments for the developer's business code
  • Development efficiency is relatively high

Disadvantage

As the saying goes, if you have something, you will lose. We have gained these conveniences, but there are some corresponding shortcomings and shortcomings.

  • sql optimization is more difficult, various operations are finally sent to db, and sql is automatically generated by hibernate, it is relatively difficult for developers to intervene in the sql that needs to be executed eventually
  • Getting started with hibernate is relatively easy, but difficult to master
  • For complex dynamic SQL, a lot of judgments need to be written in the code for assembly, and the support for dynamic SQL is relatively lacking.

Therefore, Hibernate is only suitable for simple systems, or systems with tight development cycles, and projects that are not highly optimized for SQL.

MyBatis

Mybatis puts sql under the control of developers, so developers are more free and without too many restrictions. They can realize all kinds of weird business and logic of various companies. In terms of SQL optimization, they can also It can be said that good or bad has its own way to give full play to the programmer's ability. And Mybatis just helps us optimize the repetitive work to the extreme, such as the process of operating db, the splicing of dynamic SQL, the result and the mapping of objects are all processed for us, and we don't need too much care and attention. Let us put more energy on the preparation of sql, so this is also favored by many domestic manufacturers, so if you want to enter a major factory in the next year, you must master it.

In short, MyBatis:

  • Is an excellent persistence layer framework
  • Almost all the JDBC code and the process of setting parameters and obtaining result sets are avoided.
  • Use simple XML or annotations to configure and map native information, and map interfaces and Java entity classes to records in the database

The specific steps of mybatis development project

The above is so good, after all, the mule is a horse to be pulled out for a walk, so next we will build a shelf for the Mybatis project together, which will be filled in the next article. And make a presentation

Introduce mybatis maven configuration into the Spring project

The first step is to introduce mybatis

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
</dependency>

For the myba.ve.version version above, you can find the latest version in the maven repository or the version required by the company.

Create mybatis configuration file

When we introduce Mybatis, the next step is to write the configuration file of Mybatis. The configuration file is in xml format and is generally placed in the resource directory.

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>
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatisdemo?characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </properties>
    <environments default="development">
        <environment id="development">
            <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="mapper/user.xml"/>
    </mappers>
</configuration>

This file is mainly for the global configuration of mybatis, such as the configuration of data sources and transactions. For example, the datasource element above is used to configure the data source, and some configuration information of the database needs to be specified in the data source; here I set it up. You can change this code according to your own database for the continuous information of the database.

It doesn't matter if you don't know the code very well now, and subsequent articles will explain and analyze it step by step.

Create mapper xml file

This file represents all our operations on the table. After completion, it will be introduced by the configuration file of mybatis above, as shown below

<mappers>
    <mapper resource="mapper/user.xml"/>
</mappers>

There can be multiple mapper files in the mappers element. There may be many tables that need to be manipulated in the project we develop. Then there will be a lot of mapper xml files. We all need to import them in the mappers element, and then mybatis will use them. Generally speaking, a table corresponds to a mapper file.

Create Mapper interface

Above we created the configuration file and table operation file of mybatis. Later, we need to use a Mapper interface to establish a mapping relationship with the mapper.xml in the step above.

Later, when we call the methods in the Mapper interface, we will indirectly call the SQL operations of various data in the mapper xml.

Mapper interface and xml file association

We created the Mapper interface and the xml file above, but how are the two related?

This requires configuration in uesr.xml, as shown below

<mapper namespace="zhonghu.mybatis.chat01.UserMapper"

Note that the value of the namespace above corresponds to the complete reference of the UserMapper interface. Through this namespace, the UserMapper interface can establish a mapping relationship with user.xml.

There are many db operations in user.xml. These operations will establish a mapping relationship with the methods in the UserMapper interface. When the methods in UserMapper are called, the corresponding operations in user.xml will be indirectly called.

For example, there is the following configuration in user.xml:

<!-- 批量插入 -->
<insert id="insertBatch" parameterType="map">
    <![CDATA[ INSERT INTO `user` (`id`, `name`, `age`, `salary`) VALUES ]]>
    <foreach collection="list" separator="," item="item">
        (#{item.id}, #{item.name}, #{item.age}, #{item.salary})
    </foreach>
</insert>

And there is an insertBatch method in UserMapper that corresponds to the above insert batch insert, as follows:

/**
 * 批量插入用户信息
 *
 * @param userModelList
 */
void insertBatch(List<UserModel> userModelList);

So when we call the insertBatch method in UserMapper, we will indirectly call the operation id="insertBatch" in user.xml.

Now we can use mybatis to operate db.

The interface and mapper xml are mapped together and indirectly called, which is implemented through java dynamic proxy.

Get the Mapper interface through mybatis to perform operations on db

As we said above, we can perform operations on db through the mapper interface. The main code for obtaining Mapper is as follows:

SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);

The core components in mybatis are used in the above code, let's take a look specifically.

Introduction to Mybatis core objects

SqlSessionFactoryBuilder

This is a builder that is used to build a SqlSessionFactory object. SqlSessionFactoryBuilder can read the configuration file of mybatis and then build a SqlSessionFactory object.

SqlSessionFactoryBuilder parses the mapping relationship between mybatis configuration files, mapper xml files, mapper xml files, and Mapper interfaces, and then puts them in the java object. The java object exists in the memory, and the access in the memory will be very fast, then Every time we use it, we don’t need to parse the xml again. After SqlSessionFactoryBuilder parses the configuration, the generated object is SqlSessionFactory. This is a heavyweight object. It is time-consuming to create it, so we generally create a db. A SqlSessionFactory object will always exist during system operation, and the SqlSessionFactoryBuilder can be released when it runs out.

SqlSessionFactory

You can know by the name that this is a factory, a factory used to create a SqlSession.

As mentioned above, SqlSessionFactory is a heavyweight object. Generally, a db corresponds to a SqlSessionFactory object, which will always exist during system operation.

SqlSessionFactory is an interface, this interface has two implementations DefaultSqlSessionFactory and SqlSessionManager, generally through SqlSessionFactoryBuilder to create SqlSessionFactory objects.

There are two main ways to create SqlSessionFactory objects through SqlSessionFactoryBuilder, one is to read the mybatis configuration file, and the other is to hard code.

SqlSession

We need to obtain a Connection connection to operate the database through jdbc, and then use this connection to operate on the db. SqlSession in mybatis is similar to the Connection connection object in jdbc, which is called the Sql session object in mybatis. Generally, we use a db operation A SqlSession object, so this object is generally at the method level. After the method ends, the object is destroyed. This object can be obtained by calling the sqlSessionFactory.openSession method.

We can directly call various db operations in mapper xml through the SqlSession object, we need to specify the id of the specific operation, and the format of the id is the id of the namespace. operation.

Mapper interface

We can directly call the db operation in mapper xml through SqlSession, but a simpler and recommended way is to use the Mapper interface. The methods in the Mapper interface and various db operations in the mapper xml file establish a mapping relationship, which is through the Mapper interface. The full name + method name is associated with the namespace + specific operation id in the mapper xml, and then we can directly call the method in the Mapper interface to indirectly operate the db. It is convenient to use, and the Mapper interface needs to be obtained through SqlSession and passed Enter the Class object corresponding to the Mapper interface, and then return an instance of this interface, such as:

UserMapper mapper = sqlSession.getMapper(UserMapper.class);

At last

  • If you feel that you are rewarded after reading it, I hope to pay attention to it. By the way, give me a thumbs up. This will be the biggest motivation for my update. Thank you for your support.
  • Welcome everyone to pay attention to my public account [Java Fox], focusing on the basic knowledge of java and computer, I promise to let you get something after reading it, if you don’t believe me, hit me
  • Seek one-click triple connection: like, forward, and watching.
  • If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love.

——I am Chuhu, and I love programming as much as you.

Welcome to follow the public account "Java Fox" for the latest news

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/113571825