Getting to Know Mybatis -- Mybatis Quick Start Nanny-Level Tutorial (1)


foreword

In order to consolidate the knowledge learned, the author tried to start publishing some blogs of learning notes for future review. Of course, it would be great if it could help some newcomers learn new technologies. The author is a piece of food. If there are any mistakes in the records in the article, readers and friends are welcome to criticize and correct.
(The reference source code of the blog can be found in the resources on my homepage. If you have any questions during the learning process, please feel free to ask me in the comment area)


First, know mybatis

1. What is mybatis

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

2. jdbc disadvantages

  • The database connection is created when it is used, and released when it is not used. Frequent connection switching and closing of the database will cause waste of database resources and affect the performance of the database.

  • The sql statement is hard-coded in the java program. If you modify the sql statement, you need to recompile the java code, which is not conducive to system maintenance.

  • Set parameters in PreparedStatement, hardcode the placeholder position and set parameter values, and modify the sql statement without recompiling the java code

  • When traversing the result set data from result, there is hard coding, and the fields of the obtained table are hard coded

  • sample code

insert image description here

3. Mybatis advantages

  • Flexibility: MyBatis allows you to directly write native SQL statements, providing high flexibility. You can write any complex SQL according to your needs, so as to meet various business needs.

  • Ease of use: MyBatis allows you to easily separate SQL statements from Java code through XML configuration files and annotations, making the code structure clearer and easier to maintain.

  • Simple mapping: MyBatis provides a simple mapping method, which can automatically map the fields in the database table to the properties of the Java object, reducing the complexity of data conversion.

  • Good scalability: MyBatis provides a rich plug-in interface, you can write custom plug-ins to extend the functions of MyBatis to meet specific needs.

  • Integration with other frameworks: MyBatis can be seamlessly integrated with popular frameworks such as Spring and Spring Boot to provide a more complete solution.

  • Community Support: MyBatis has an active developer community that provides users with rich documentation, tutorials and support. This helps to quickly find solutions when problems are encountered.

4. MyBatis framework solves JDBC disadvantages

For the disadvantages of JDBC programming, MyBatis provides the following solutions, as follows.

  • Problem 1: Frequent creation and release of database links will cause waste of system resources, thereby affecting system performance.

Solution: Configure the data connection pool in SqlMapConfig.xml, and use the connection pool to manage the database connection.

  • Problem 2: SQL statements are hard-coded in the code, making the code difficult to maintain. In the development of practical applications, the possibility of SQL changes is relatively large. In traditional JDBC programming, SQL changes need to change Java code, which violates the principle of opening and closing.

Solution: MyBatis configures the SQL statement in the MyBatis mapping file, realizing the separation from the Java code.

  • Question 3: There is hard coding in using preparedStatement to pass parameters to placeholders, because the where condition of the SQL statement is not necessarily certain, and may be more or less. Modifying SQL requires modifying the code, making the system difficult to maintain.

Solution: MyBatis automatically maps Java objects to SQL statements, and defines the type of input parameters through parameterType in Statement.

  • Question 4: JDBC has hard-coded result set parsing (query column names). Changes in SQL lead to changes in parsing codes, making the system difficult to maintain.

Solution: MyBatis automatically maps SQL execution results to Java objects, and defines the type of output results through resultType in Statement.

  • sample code

insert image description here

Two, mybatis entry case

(For detailed code, see mybatis source code re_mb_mapper module on personal homepage)

1. Demand analysis and operation steps

insert image description here

2. Create table tb_user, entity class and Mapper interface

  1. Create database tables
  • Check for phrases
create database mybatis;
use mybatis;

drop table if exists tb_user;

create table tb_user(
	id int primary key auto_increment,
	username varchar(20),
	password varchar(20),
	gender char(1),
	addr varchar(30)
);

INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '', '北京');
INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');

  • Show results

insert image description here

  1. Create entity classes and their corresponding Mapper interfaces
  • Create entity class
//省略setter、getter方法和toString方法
public class User {
    
    

    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String addr;

  • Create the Mapper interface of the corresponding entity class user
public interface UserMapper {
    
    

}

3. Create maven module re_mb_demon

insert image description here

4. Import related dependencies in the pom.xml configuration file

<dependencies>
        <!--mybatis 依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <!--mysql 驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <!--junit 单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>


        <!-- 添加slf4j日志api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.20</version>
        </dependency>
        
        <!-- 添加logback-classic依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        
        <!-- 添加logback-core依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>
    </dependencies>

5. Configure related files

  1. Create and configure the console output log logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--
        CONSOLE :表示当前的日志信息是可以输出到控制台的。
    -->
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%level]  %cyan([%thread]) %boldGreen(%logger{
    
    15}) - %msg %n</pattern>
        </encoder>
    </appender>

    <logger name="org.example" level="DEBUG" additivity="false">
        <appender-ref ref="Console"/>
    </logger>


    <!--

      level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
     , 默认debug
      <root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
      -->
    <root level="DEBUG">
        <appender-ref ref="Console"/>
    </root>
</configuration>
  1. Create and configure database connection information mabatis_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">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    
<!--指定映射配置文件的位置-->
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
    
</configuration>

  1. Create and configure the mapping configuration file UserMapper.xml
<?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">
        
<!--namespace:名称空间-->
<mapper namespace="org.example.mapper.UserMapper">

<!--id: select标签的唯一标识符-->
<!--resultType: 返回值类型-->
    <select id="selectAll" resultType="org.example.pojo.User">
        select *
        from tb_user;
    </select>
    
</mapper>

6. Create and write the mock test class MybatisDemon

/**
 * Mybatis 快速入门代码
 */
public class MyBatisDemo {
    
    

    public static void main(String[] args) throws IOException {
    
    

        //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
        //定义配置文件路径
        String resource = "mybatis-config.xml";
        //通过mybatis提供的resources资源加载类对象返回一个字节输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //将字节输入流传入SqlSessionFactoryBuilder()的build()方法,返回一个SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3. 执行sql
        //参数:名称空间 + id
        List<User> users = sqlSession.selectList("org.example.mapper.UserMapper.selectAll");
        System.out.println(users);

        //4. 释放资源
        sqlSession.close();

    }
}

7. Running results and file structure

  • operation result

insert image description here

  • file structure

insert image description here

8. Solve the warning prompt of configuring SQL statement

  1. Problem Description

insert image description here

  1. solution

(you also need to fill in the database name)

insert image description here

3. Mybatis mapper agent development

(Coding is based on the mybatis entry case, see the personal homepage mybatis source code re_mb_mapper module for detailed code)

1. Getting to know mapper agent development for the first time

  • Method 1: In an XML mapping file (such as UserMapper.xml in the case), an infinite number of mapping statements can be defined, so that the XML header and the document type declaration part become insignificant. The rest of the documentation is straightforward and easy to understand. It defines a mapping statement named "selectAll" in the namespace "org.example.mapper.UserMapper", so that you can call the mapping statement with the fully qualified name "org.example.mapper.UserMapper.selectAll" , as in the starter case mock test class:
 List<User> users = sqlSession.selectList("org.example.mapper.UserMapper.selectAll");
  • Method 2: You may notice that this method is similar to the method of calling a Java object with a fully qualified name. This way, the name can be mapped directly to a mapper class of the same name in the namespace, and the mapped select statement is matched to the method with the corresponding name, parameters, and return type. So you can call the method on the corresponding mapper interface as above without breaking a sweat, like this:
 UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = userMapper.selectAll();

The second method has many advantages. First, it does not depend on the string literal value and is safer. Second, if your IDE has code completion function, then code completion can help you quickly select the mapped SQL statement .

2. mybatis mapper proxy development rules

insert image description here

3. Coding example according to agent development rules

  1. Define the Mapper interface with the same name as the SQL mapping file, and place the Mapper interface and the SQL mapping file in the same directory
  • step one

insert image description hereinsert image description here

  • step two

insert image description here

  1. Set the namespace attribute of the SQL mapping file (UserMapper.xml) to the fully qualified name of the Mapper interface

insert image description here

  1. Define the method in the Maper interface, the method name is the id of the sql statement in the SQL file, and keep the parameter type and return value type consistent
public interface UserMapper {
    
    
    List<User> selectAll();
}

4. Coding (simulation test class MybatisDemon)

insert image description here

  1. Simulation test class running results

insert image description here

6. Scan the mapper mapping file (mybatis_config.xml) by package scanning

insert image description here

Four, mybatis core configuration file

1. Configuration

MyBatis configuration files contain information about settings and properties that deeply affect MyBatis behavior. The top-level structure of the configuration document is as follows:

.configuration(配置)
   .properties(属性)
   .settings(设置)
   .typeAliases(类型别名)
   .typeHandlers(类型处理器)
   .objectFactory(对象工厂)
   .plugins(插件)
   .environments(环境配置)
       .environment(环境变量)
           .transactionManager(事务管理器)
           .dataSource(数据源)
   .databaseIdProvider(数据库厂商标识)
   .mappers(映射器)

Note: When configuring each label, you need to follow the order

2. Environment configuration (environments)

  1. Explanation of application scenarios

MyBatis can be configured to adapt to a variety of environments. This mechanism helps to apply SQL mapping to a variety of databases. There are many reasons to do so in reality. For example, development, test, and production environments need to have different configurations; or you want to use the same SQL mapping in multiple production databases with the same schema. There are many similar usage scenarios.

But remember: Although multiple environments can be configured, only one can be selected per instance of SqlSessionFactory.

  1. Introduction to Environment Configuration Operations

So, if you want to connect to two databases, you need to create two SqlSessionFactory instances, one for each database. And if there are three databases, three instances are needed, and so on, it is very simple to remember:

每个数据库对应一个 SqlSessionFactory 实例

To specify which environment to create, just pass it as an optional parameter to SqlSessionFactoryBuilder. Two method signatures that can accept environment configurations are:

   SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment);
   SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment, properties);

If the environment parameter is omitted, the default environment will be loaded, as follows:

   SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
   SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, properties);

The environments element defines how to configure the environment.

<!--environments:配置数据库连接环境信息。可以配置多个environment-->
<!--default: 切换不同的environment-->
<environments default="development">
<environment id="development">
  <transactionManager type="JDBC">
    <property name="..." value="..."/>
  </transactionManager>
  <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>

Note some key points:

   默认使用的环境 ID(比如:default="development")。
   每个 environment 元素定义的环境 ID(比如:id="development")。
   事务管理器的配置(比如:type="JDBC")。
   数据源的配置(比如:type="POOLED")。

The default environment and environment ID are as their names suggest. Environments can be named whatever they want, but make sure the default environment ID matches one of the environment IDs.

insert image description here

3. Type aliases (typeAliases)

  1. By matching a single type alias

A type alias sets an abbreviated name for a Java type. It is only used for XML configuration and is intended to reduce redundant writing of fully qualified class names. For example:

<typeAliases>
  <typeAlias alias="Author" type="domain.blog.Author"/>
  <typeAlias alias="Blog" type="domain.blog.Blog"/>
  <typeAlias alias="Comment" type="domain.blog.Comment"/>
  <typeAlias alias="Post" type="domain.blog.Post"/>
  <typeAlias alias="Section" type="domain.blog.Section"/>
  <typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>

When configured like this, Blog can be used anywhere domain.blog.Blog is used.

  1. Configure type aliases through the package

You can also specify a package name, and MyBatis will search for the required Java Bean under the package name, for example:

<typeAliases>
  <package name="domain.blog"/>
</typeAliases>
  • example

(mybatis_config.xml)

insert image description here

(UserMapper.xml)

insert image description here

  1. Configuration of type aliases with annotations

Each Java Bean in the package domain.blog, in the absence of annotations, will use the bean's initial lowercase unqualified class name as its alias. For example, the alias of domain.blog.Author is author; if there is an annotation, the alias is its annotation value. See the example below:

@Alias("author")
public class Author {
    
    
    ...
}

Summarize

Everyone is welcome to leave a message for exchange and criticism. If the article is helpful to you or you think the author's writing is not bad, you can click to follow, like, and bookmark to support.
(The reference source code of the blog can be found in the resources on my homepage. If you have any questions during the learning process, please feel free to ask me in the comment area)

Guess you like

Origin blog.csdn.net/HHX_01/article/details/130581978