Introduction to MyBatis framework theory and practice




Insert image description here


1. Introduction to MyBatis framework


MyBatis is an open source project under the Apache Software Foundation, formerly the iBatis framework.

In 2010, this project was moved from the Apache Software Foundation to Google Code and renamed MyBatis. In November 2013, it was moved to GitHub (GitHub is a hosting platform for open source and private software projects).

MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures and advanced mapping (multiple tables). MyBatis avoids almost all JDBC code and manual setting of parameters and obtaining result sets. It encapsulates the process of operating the database of jdbc, so that developers only need to focus on SQL itself, without spending energy to deal with jdbc's complicated process codes such as registering drivers, creating connections, creating statements, manually setting parameters, and retrieving result sets. . MyBatis can use simple XML or annotations to configure and map native types, interfaces, and Java POJOs (Plain Old Java Objects) into records in the database.


1.1 Advantages of MyBatis

  1. Easy to learn: MyBatis itself is small and simple. There are no third-party dependencies. The simplest installation only requires two jar files + configuring several SQL mapping files.
  2. Flexible to use: MyBatis does not impose any impact on the existing design of the application or database. SQL statements are written in XML to facilitate unified management and optimization.
  3. Decouple SQL from program code: By providing a DAO layer, business logic and data access logic are separated, making the system design clearer, easier to maintain, and easier to perform unit testing. The separation of SQL statements and code improves maintainability.

1.2 MyBatis shortcomings

  1. Writing SQL statements requires a lot of work, especially when there are many fields and related tables.
  2. SQL statements depend on the database, resulting in poor database portability and the inability to replace the database.
  3. The framework is still relatively crude and there are still some missing functions.

2. Overall architecture of MyBatis framework

Insert image description here

1、Configuration file
Global configuration file (core configuration file): mybatis-config.xml, function: configure data source (configure database connection information), introduce mapping file
Mapping file: XxMapper.xml, function: configure sql statements, parameters, result set encapsulation type, etc.

2、SqlSessionFactory
Function: Get SqlSession
to build through new SqlSessionFactoryBuilder().build(inputStream), inputStream: read the IO stream of the configuration file

3、SqlSession
Function: Perform CRUD operations

4、Executor
Executor, SqlSession completes specific CRUD by calling it

5、Mapped Statement
Configured in the mapping file, it contains 3 parts:
specific sql, parameter types required for sql execution, and encapsulation type of sql execution results. Parameter types
and result set encapsulation types include 3 types:
HashMap, basic data type, pojo


3. Introduction to MyBatis ORM


Object Relational Mapping: It is a programming technology used to convert data between different types of systems in object-oriented programming languages. In effect, it actually creates a "virtual object database" that can be used in programming languages. There are many free and paid ORM products available today, and some programmers prefer to create their own ORM tools.

Two mapping methods of MyBatis:
1. Through XML mapping
2. Through annotations


4. Introduction to MyBatis framework development

4.1 Construction of entry-level cases

4.1.1 Prepare SQL data

create table user (
  id int primary key auto_increment,
  username varchar(20) not null,
  birthday date,
  sex char(1) default '男',
  address varchar(50)
);

insert into user values (null, '刘亦菲','1988-10-24','女','湖北武汉');
insert into user values (null, '胡歌','1988-11-12','男','上海');
insert into user values (null, '李现','1991-10-30','男','湖北武汉');
insert into user values (null, '宋祖儿','1999-03-22','女','北京');

4.1.2 Create a new SpringBoot project

The structure is as follows:
Insert image description here

4.1.3 pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.6.RELEASE</version>
    </parent>

    <groupId>com.snow</groupId>
    <artifactId>studyMybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>


    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

</project>

4.1.4 Configuration file

Write the configuration in the application.yml file under resource:

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.0.108:3306/study_mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver


# mybatis 配置
mybatis:
  # 配置实体类所在的包
  type-aliases-package: com.snow.po
  # 配置 xml 文件所在的包
  mapper-locations: classpath:com/snow/mapper/*.xml
  configuration:
    # 开启驼峰命名
    map-underscore-to-camel-case: true

logging:
  level:
    com.snow.mapper: debug

Entity class

import java.io.Serializable;
import java.time.LocalDate;

public class User implements Serializable {
    
    

    //  id int primary key auto_increment,
    private Integer id;

    //  username varchar(20) not null,
    private String username;

    //  birthday date,
    private LocalDate birthday;

    //  sex char(1) default '男',
    private String sex;

    //  address varchar(50)
    private String address;

    public User() {
    
    
    }

    public User(Integer id, String username, LocalDate birthday, String sex, String address) {
    
    
        this.id = id;
        this.username = username;
        this.birthday = birthday;
        this.sex = sex;
        this.address = address;
    }
	 //SET GET 略
}


4.1.5 mapper sum mapper.xml

Insert image description here
mapper class

import com.snow.po.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    
    
    List<User> getList();
}

mapper.xml file

<?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.snow.mapper.UserMapper">
    <select id="getList" resultType="User">
        select * from user ORDER BY id DESC
    </select>
</mapper>

4.1.6 Build Controller

@RestController
@RequestMapping("/user")
public class UserController {
    
    
    @Autowired
    private UserMapper userMapper;
    
	@GetMapping("/getList")
    public List<User> getList(){
    
    
        return userMapper.getList();
    }
}

4.2 Testing

After completing the above writing, start the project for testing
and enter http://localhost:8080/user/getList

The following is the data in the table obtained
Insert image description here

A simple introductory case is completed. Isn't it much more convenient than JDBC?


5. Summary

MyBatis is a popular Java persistence framework used to simplify interaction with relational databases. The following is my summary of getting started with MyBatis:

  1. Introducing dependencies: First, introduce MyBatis related dependencies into the project. This can be configured using build tools such as Maven or Gradle.

  2. Configure the data source: In the MyBatis configuration file, configure the connection information with the database, including the database URL, user name and password, etc.

  3. Define mapping files: MyBatis uses mapping files to map Java objects to database tables. In the mapping file, define the mapping relationship between SQL statements and parameters.

  4. Write entity classes: Create entity classes corresponding to database tables, and use annotations or XML to configure mapping relationships with fields.

  5. Write DAO interface: define the interface for persistence operations, and declare the database operations that need to be performed in the interface.

  6. Configure DAO mapping: In the MyBatis configuration file, configure the mapping relationship of the DAO interface and bind the interface to the mapping file.

  7. Get SqlSession: Get the SqlSession object through SqlSessionFactory. SqlSession is the core class of MyBatis and is used to execute SQL statements.

  8. Perform database operations: Call methods in the DAO interface through the SqlSession object to perform database operations, such as inserts, queries, updates, and deletes.

  9. Release resources: After the operation is completed, close the SqlSession.

MyBatis makes the interaction between Java programs and databases easy and flexible through simple configuration and writing a small amount of code. To get started with MyBatis, you need to understand the above basic steps, learn and master the core concepts and usage of MyBatis. Hope this summary is helpful to you!



Insert image description here

Guess you like

Origin blog.csdn.net/m0_60915009/article/details/132773949