Easy to understand -- Mybaties entry code is a must for farmers to avoid pits

Posted by crazylegseddie on Tue, 01 Feb 2022 08:56:17 +0100

Mybatis actual combat

Tip: you can add the directories of all articles in the series here. You need to add the directories manually
For example: the first chapter is the use of pandas, an introduction to Python machine learning

Tip: after writing the article, the directory can be generated automatically. For how to generate it, please refer to the help document on the right

preface

Mybatis
For example, with the continuous development of big data, the technology of mybats is becoming more and more important. Many people have opened the learning framework. This paper introduces the basic content of mybats.

Tip: the following is the main content of this article. The following cases can be used for reference

1, What is Mybaties?

Mybatis is an excellent persistence layer framework, which supports customized SQL, stored procedures and advanced mapping. Mybatis avoids almost all JDBC code and manually setting parameters and getting result sets. Mybatis can use simple XML or annotations to configure and map native information, and map ordinary objects in jav to records in the database.
Simply put: MyBatis is a semi-automatic ORM framework, whose essence is the encapsulation of JDBC. Using MyBatis mainly requires programmers to write SQL commands without writing a line of JDBC code.
On the contrary, Hibernate is a fully automatic ORM framework; Because Hibernate creates a complete mapping between Java objects and database tables, it can operate the database completely with the idea of object-oriented. Programmers do not need to write SQL statements, while MyBatis also needs to write SQL statements. Therefore, it is semi-automatic and the workload is greater than that of Hibernate.

Why is semi automated Mybatis more popular than automated Hibernate?

Since MyBatis requires handwritten SQL statements, the workload is greater than that of hibernate. However, it is precisely because of the custom SQL statement that its flexibility and optimizability exceed that of Hibernate; MyBatis leaves the work of handwritten SQL statements to developers, which can define SQL more accurately, be more flexible, and facilitate performance optimization. The performance of two SQL statements that complete the same function may differ by more than ten to dozens of times. In the Internet system with high concurrency and fast response requirements, the impact on performance is more obvious

In short, MyBatis has the advantages of less encapsulation, diversified mapping, support for stored procedures and SQL statements
It meets the requirements of high concurrency, big data, high performance and high response of the Internet, making it replace Hibernate
Java is the preferred persistence framework in the Internet. For those with low performance requirements, such as internal management system, ERP, etc
Hibernate can be used.

Benefits of using frameworks:

  1. Reduce code reuse
  2. The standardization of code structure can reduce the cost of communication between programmers and future maintenance
  3. With the accumulation of knowledge, those experienced people can design frameworks and domain components without being limited to low-level programming

2, Basic use of Mybatis

1. Download address of mybatis jar package

https://github.com/mybatis/mybatis-3/releases

2 Introduction to mybatis jar package


3 Introduction to core API

3.1 core API

SqlSessionFactoryBuilder
The role of SqlSessionFactoryBuilder is to create SqlSessionFactory interface objects using builder mode.
SqlSessionFactory
SqlSessionFactory can be considered as a database connection pool. Its function is to create SqlSession interface objects
SqlSession
If SqlSessionFactory is equivalent to a database Connection pool, then SqlSession is equivalent to a database Connection (Connection object). You can execute multiple SQL in a transaction, and then commit or roll back the transaction through its commit and rollback methods
Mapper
Mapper. It is composed of a Java interface and XML file (or annotation). It needs to give the corresponding SQL and mapping rules, and is responsible for sending SQL to execute and return results

3.2 core API workflow

3.3 life cycle

SqlSessionFactoryBuilder:
This class is used to create a SqlSessionFactory object. When the SqlSessionFactory object is created, the SqlSessionFactoryBuilder will lose its function, so it can only exist in the method of creating SqlSessionFactory, not for a long time. Therefore, the best scope of the SqlSessionFactoryBuilder instance is the method scope.

SqlSessionFactory:
The life cycle of SqlSessionFactory exists in the whole MyBatis application, so once the SqlSessionFactory is created, it must be saved for a long time until the MyBatis application is no longer used. Therefore, it can be considered that the life cycle of SqlSessionFactory is equivalent to the MyBatis application cycle. Since SqlSessionFactory is a connection pool to the database, it occupies the connection resources of the database. If you create multiple sqlsessionfactories, there will be multiple database connection pools, which is not conducive to the control of database resources. It will also lead to the depletion of database connection resources and system downtime. Therefore, try to avoid this situation. Therefore, SqlSessionFactory is a singleton, so that it can be shared in the application.

SqlSession:
SqlSession should survive in a business request. After processing a complete request, close the connection and return it to SqlSessionFactory. Otherwise, the database resources will be consumed quickly and the system will be paralyzed. Therefore, use the try... catch... finally... Statement to ensure that it is closed correctly.
Therefore, the best scope of SqlSession is the request or method scope.

Mapper:
Due to the closing of SqlSession, its database connection resources will disappear, so its life cycle should be less than or equal to the life cycle of SqlSession. Mapper represents the business processing in a request, so it should be in a request. Once the relevant business is processed, it should be discarded.
4. Mybatis configuration file
https://mybatis.org/mybatis-3/zh/configuration.html
There are two types of configuration files in Mybatis:
 global configuration file
Mapping configuration file

4.1 global configuration file
The name of the global configuration file is user-defined and needs to be placed in the src directory in the Java project project.
The function of global configuration file is to complete some global configurations, such as Mybatis framework settings, alias settings, environment settings, specified mapping configuration file and other related configurations.

<?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>
</configuration>

4.1.1 properties tab
Attribute definitions in the Mybatis configuration file. The Properties tab allows you to define properties internally or externally in the properties file. Whether it is an internal definition or an external definition, you can use ${name} to get the value.
Internal definition in configuration file

<properties>
<property name="jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="jdbc.url"
value="jdbc:mysql://localhost:3306/bjsxt"/>
<property name="jdbc.username" value="root"/>
<property name="jdbc.password" value="root"/>
</properties>

External definition in configuration file

<properties resource="db.properties"></properties>

db.properties file:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/bjsxt
jdbc.username=root
jdbc.password=3306

4.1.2 typeAliases label
Type alias sets an abbreviated name for a Java type

<typeAliases>
<typeAlias alias="user" type="com.bjsxt.pojo.User" />
</typeAliases>

You can also specify a package name. MyBatis will search for the required Java beans under the package name

<typeAliases>
<package name="com.bjsxt.pojo"/>
</typeAliases>

4.1.4.1 transactionManager node
Transaction processor.
There are two types of transaction managers in MyBatis (that is, type="[JDBC|MANAGED]")
JDBC: this configuration directly uses JDBC's commit and rollback facilities. It relies on the connection obtained from the data source to manage the transaction scope.
MANAGED: no transaction processing.
4.1.4.2 dataSource label
The dataSource element uses the standard JDBC data source interface to configure the resources of the JDBC connection object.
UNPOOLED: use direct connection.
POOLED: use pool connection.
JNDI: connect using JNDI
4.1.5 mapper label
Specify mapping profile
Specifies the mapping profile with respect to the classpath

<mappers>
<mapper resource="com/zhang/mapper/UserMapper.xml"/>
</mappers>

Specify the mapping profile using the filter: / / / protocol

<mappers>
<mapper
url="file:///D:\code\mybatis\src\com\zhang\mapper\UserMapper.xml"
/>
</mappers>

Specify mapping interface

<mappers>
<mapper class="com.zhang.mapper.UserMapper"/>
</mappers>

Specify the mapping interface by package name

<mappers>
<package name="com.zhang.mapper"/>
</mappers>

4.2 mapping profile
The mapping configuration file is mainly used to write sql statements, specify the mapping relationship of the result set, and some cache configurations.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhang.mapper.UserMapper">
</mapper>

4.2.1 resultMap label
Specifying the mapping relationship between query result set and object is the most complex and powerful label.
id: unique identification.
Type: the full name of the class, or a type alias

<resultMap id="userMapper" type="com.zhang.pojo.User">
   <id property="userid" column="user_id"/>
   <result property="username" column="user_name"/>
</resultMap>

4.2.1.1 id label
Specifies the value in the primary key that identifies a result mapping.

4.2.1.2 result label
Specifies a value in a non primary key that identifies a result mapping.

4.2.1.3 association label
Usually used to map one-to-one relationships.

4.2.1.4 collection label
It is usually used to map one to many relationships.

4.2.2 select tag
Query statement.
id: the unique identifier of the current query statement. The value of this attribute cannot be duplicate.
parameterType: Specifies the parameter type. This attribute is optional. Because MyBatis can infer the parameters of the specific incoming statement through the type handler.
resultType: the full name or alias of the class from which the result is expected to be returned.
resultMap: use the resultMap tag to process the result set mapping.

<select id="selectUser" parameterType="int" resultType="com.zhang.pojo.User">
    select * from users where userid = #{userid}
</select>

4.2.3 insert tag
Add a statement.
id: the unique identifier of the currently added statement. The value of this attribute cannot be repeated.
parameterType: Specifies the parameter type and can be given an alias. This attribute is optional.

<insert id="insertUser" parameterType="com.zhang.pojo.User">
insert into users values(default ,#{username},#{usersex})
</insert>

4.2.4 update tag
UPDATE statement.
id: the unique identifier of the current update statement. The value of this attribute cannot be repeated.
parameterType: Specifies the parameter type and can be given an alias. This attribute is optional.

<update id="updateUser" parameterType="com.bjsxt.pojo.User">
update users set username=#{username},usersex=#{usersex} where
userid =#{userid}
</update>

4.2.5 delete tag
Delete statement.
id: the unique identifier of the current deletion statement. The value of this attribute cannot be duplicate.
parameterType: Specifies the parameter type and can be given an alias. This attribute is optional.

<delete id="deleteUser" parameterType="int">
    delete from users where userid = #{userid}
</delete>

4.2.6 sql Tags
Can be used to define reusable SQL code snippets. The clip is introduced through the tag.
id: the unique identifier of the current SQL fragment. The value of this attribute cannot be duplicate.

<sql id="userColumns">
userid,username,usersex
</sql>
<select id="selectUser" parameterType="int" resultType="com.zhang.pojo.UserMapper">
select <include refid="userColumns"/> from users
</select>

Summary of configuration environment

The first step is to configure the global configuration file
The individual file header of the global configuration has been recorded on it, and the little partners can go back to the ancients;
My global configuration file code is as follows: (for reference)

<?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>
    <!--introduce db file-->
    <properties resource="db.properties"></properties>
    <!--Configuration environment-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
        <environment id="text">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--Import mapping profile-->
    <mappers>
        <mapper class="com.zhang.Mapper.UserMapper"/>
    </mappers>
</configuration>

The second step is to configure the mapping profile:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD com.zhang.Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhang.Mapper.UserMapper">
    <resultMap id="userMapper" type="com.zhang.POJO.Users">
        <id property="userid" column="userid"/>
        <result property="username" column="username"/>
        <result property="usersex" column="usersex"/>
    </resultMap>
    <select id="selectUsers" parameterType="int" resultType="com.zhang.POJO.Users">
        select * from users where userid = ${userid}
    </select>
    <insert id="insertUser" parameterType="com.zhang.pojo.User">
        insert into users values(default ,#{username},#{usersex})
    </insert>

</mapper>

It should be noted that whether the configuration of namespace is correct or not, and the new partners may have incorrect configuration of Mapper tag in the global configuration file; If the configuration file cannot be found when running the code, remember to look back and see if the Mapper tag is correct;

summary

Tip: the above is my summary of Mybatis. The first part has passed 10000 words, and the second part will be updated in 3 days. Ha, my favorite little partner, pay attention to collection ha:

Topics: Python Mybatis Back-end SSM