SpringBoot series (8): MyBatis version of xml configuration

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/mu_wind/article/details/100034561

1 MyBatis Introduction

MyBatis is a standard ORM framework, is widely used in various business development. MyBatis supports common SQL queries, stored procedures and advanced mapping class persistence framework. MyBatis eliminates almost all of the code and to manually set parameters JDBC package and retrieve the result set. MaBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJO (Plain Old Java Objects, ordinary Java Objects) to database records in.

Object-Relational Mapping (Object Relational Mapping, ORM) to solve for the model is a phenomenon occurring not match each object relational database technology. Simply put, by using the ORM metadata that describes the mapping between the object and the database, the program objects are automatically persisted to a relational database.

1.1 Analysis of strengths and weaknesses

advantage:

  1. SQL unified extracted, to facilitate unified management and optimization
  2. SQL decouple code and the data access logic and business logic separated from the system design more clearly, easier to maintain, easier to unit test
  3. Providing a mapping label, field support ORM object relationship mapping database
  4. Tags provide object-relational mapping, support for object-relational component maintenance
  5. Flexible writing dynamic SQL, support for a variety of conditions to dynamically generate different SQL

Disadvantages:

  1. When writing SQL statements heavy workload, especially in the field more, the association table for a long time, especially
  2. SQL statement depends on the database, resulting in poor portability database

1.2 Mybatis important concepts

  1. Mapper Configuration : You can use the XML Mapper configuration files to achieve based, can also be implemented using Java annotations based MyBatis annotations, and can even use API MyBatis provides to achieve.
  2. Mapper Interface : refers to a self-defined interface to the operating data, similar to the interface commonly referred to as DAO. Early Mapper need to customize the interface to achieve, now MyBatis will automatically create a dynamic proxy object Mapper interface. Mapper interface methods typically one correspondence relationship with Mapper configuration file select, insert, update, delete, etc. XML node.
  3. Executor : MyBatis to do all the Mapper statements are carried out by Executor, Executor of MyBatis is a core interface.
  4. The SqlSession : is the key target of MyBatis, persistence operations are performed exclusive, similar to the JDBC Connection, SqlSession contains absolutely every method to execute SQL commands against the database, which encapsulates the underlying JDBC connection, can be used SqlSession instance to execute SQL statements to be mapped directly.
  5. SqlSessionFactory : MyBatis is the key target, which is a single database mapping of compiled memory mirroring. Examples can be obtained by a SqlSessionFactory SqlSessionFactoryBuilder object class, and can be constructed from SqlSessionFactoryBuilder XML configuration file or a pre-customized instance of Configuration.

1.3 Mybatis workflow

MyBatis works as follows:Here Insert Picture Description

  1. Mapper loaded first configuration of SQL mapping files, SQL or related content annotation.
  2. Create session factories, MyBatis to construct a session factory (SqlSessionFactory) information by reading the configuration file.
  3. Creating session. The session factory, MyBatis which can be created by the session object (the SqlSession), a session object is the interface, which contains the database operations increase, delete, change, method.
  4. Creating actuator. Because the session object itself can not directly manipulate the database, it uses an interface called the database actuator (Executor) to help it perform the operation.
  5. Package SQL objects. In this step, the actuator will be processed SQL encapsulate the information into an object (MappedStatement), the object comprising a SQL statement input parameters mapping information (Java simple type, the HashMap or POJO) and outputs the mapping information (Java simple type, HashMap or POJO).
  6. Operation of the database. Actuators have information packages and SQL objects to use them to access the database, and finally return to the operating result, the end of the process.

Introduction and configuration 2 MyBatis

2.1 pom.xml dependence

First, add a dependency in the pom file:

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

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

2.2 application.yml Configuration

application.yml add configuration:

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

mybatis:
  type-aliases-package: com.mutest.model
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mappers/*.xml

These configurations are what the meaning of it?

  1. spring.datasource *: configuration data sources, including the driver, connection address, user name and password
  2. LOCATION-mybatis.config : Configure mybatis-config.xml path, mybatis-config.xml configuration MyBatis basic properties;
  3. -locations mybatis.mapper : XML configuration file path corresponding Mapper;
  4. Package-aliases-mybatis.type : package entity classes arranged in the path of the project;

When Spring Boot start a data source is automatically injected into the SqlSessionFactory using SqlSessionFactory build SqlSessionFactory, then automatically injected into the Mapper, and finally we can directly use the Mapper.

2.3 startup class configuration

Add @MapperScan annotation startup class, value is defined path, Spring Boot start automatically when loaded Mapper in the path.

@SpringBootApplication
@MapperScan(value = "com.mutest.dao")
public class MutestApplication {

	public static void main(String[] args) {
		SpringApplication.run(MutestApplication.class, args);
	}
}

Or do not use @MapperScan notes, but add annotations directly @Mapper Mapper class above, for convenience, it is recommended to use the former.

3 mappers write file

3.1 Data Preparation

Database data:

DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `user_name` varchar(32) DEFAULT NULL COMMENT '用户名',
  `password` varchar(32) DEFAULT NULL COMMENT '密码',
  `age`  int DEFAULT NULL,
  `sex` enum('MALE','FEMALE'),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Creating an entity class corresponding to the table:

import lombok.Data;
import com.example.demo.enums.UserSexEnum;

/**
 * @author guozhengMu
 * @version 1.0
 * @date 2019/8/23 17:47
 * @description user表对应的实体类
 * @modify
 */
@Data
public class User {
    private Long id;
    private String userName;
    private String password;
    private int age;
    private UserSexEnum sex;
}

sex enumeration class:

public enum UserSexEnum {
    MALE, FEMALE
}

Data type of the entity classes and database fields correspond to:

  • Long correspondence bigint
  • String correspond varchar
  • int int the corresponding

3.2 mybatis-config.xml

New in the resources directory mybatis folder, the new mybatis-config.xml configuration file (the file name and path information and yml profile configuration consistent). The main configuration file common typeAliases, set the type alias, set a short name for a Java type. And only XML configuration related to the meaning of existence is only used to reduce redundancy fully qualified class name.

<?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>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer"/>
        <typeAlias alias="Long" type="java.lang.Long"/>
        <typeAlias alias="HashMap" type="java.util.HashMap"/>
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/>
        <typeAlias alias="ArrayList" type="java.util.ArrayList"/>
        <typeAlias alias="LinkedList" type="java.util.LinkedList"/>
    </typeAliases>
</configuration>

3.3 mapper write and call

3.3.1 Query Examples

1, Mapper classes corresponding to the address specified in the file:

<mapper namespace="com.example.demo.dao.UserMapper">

2, the configuration and the correspondence relation table structure class:

<resultMap id="UserMap" type="com.example.demo.model.User">
    <result column="user_name" property="userName"/>
    <result column="sex" property="sex" javaType="com.example.demo.enums.UserSexEnum"/>
</resultMap>

3, the preparation of specific sql statement

<select id="getUserList" resultMap="UserMap">
    SELECT *
    FROM test.users
</select>

4, the layer coding Dao

public interface UserMapper {
    List<User> getUserList();
}

Note: This method requires the name and id attributes in the XML configuration consistent, otherwise it will not find the way to the corresponding SQL execution.

5, controller level code

@RestController
@RequestMapping(value = "/test")
public class TestController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/mybatis")
    public List<User> test() {
        return userMapper.getUserList();
    }
}

In the Idea, the piece notes often reported "could not autowire", which is the Idea of false positives. Autowired can choose to reduce the level of detection, do not prompt enough.
Use the search function to find Autowiring for Bean Class Inspections options, the Severity levels from the previous error warning can be changed - in File - Settings - Editor.

Startup Items, browser and enter: http: // localhost: 8096 / test / mybatis, returns the result:

[{"id":1,"userName":"xiaohong","password":"123456","age":30,"sex":"MALE"}]

3.3.2 Multiplexing xml

MyBatis XML has a feature that can be reused XML, such as some of our common XML fragments can be extracted, in reference to other SQL. E.g:

<sql id="Base_Column_List" >
    id, userName, passWord, user_sex, nick_name
</sql>

<select id="getUserList" resultMap="UserMap"  >
   SELECT 
   <include refid="Base_Column_List" />
   FROM test.users
</select>  

3.3.3 dynamic sql

When we modify the database data, may be part of the field for a line of data modifications, but the specific changes which fields are not determined in advance, this time you need to use dynamic sql statement, and added if a non-empty label judgment:

<update id="updateUser" parameterType="com.neo.model.User" >
   UPDATE users 
   SET 
       <if test="userName != null">userName = #{userName},</if>
       <if test="password != null">passWord = #{passWord},</if>
       1 = 1
   WHERE 
       id = #{id}
</update>

3.3.4 Complete mapper

Accompanied by a full mapper file contains CRUD, including the CRUD:

<?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.example.demo.dao.UserMapper">
    <resultMap id="UserMap" type="com.example.demo.model.User">
        <result column="user_name" property="userName"/>
        <result column="sex" property="sex" javaType="com.example.demo.enums.UserSexEnum"/>
    </resultMap>

    <sql id="Base_Column_List">
        id, userName, password, age, sex
    </sql>

    <select id="getUserList" resultMap="UserMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM test.users
    </select>

    <select id="getUser" parameterType="Long" resultMap="UserMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM users
        WHERE id = #{id}
    </select>

    <insert id="addUser" parameterType="com.example.demo.model.User">
        INSERT INTO
            test.users
            (user_name, password, age, sex)
        VALUES
            (#{userName}, #{password}, #{age}, #{userSex})
    </insert>

    <update id="updateUser" parameterType="com.example.demo.model.User">
        UPDATE
        test.users
        SET
        <if test="userName != null">user_name = #{userName},</if>
        <if test="passWord != null">password = #{passWord},</if>
        age = #{age}
        WHERE
        id = #{id}
    </update>

    <delete id="deleteUser" parameterType="Long">
        DELETE FROM
            test.users
        WHERE
            id = #{id}
    </delete>
</mapper>

Correspondingly dao level code:

public interface UserMapper {

    List<User> getUserList();

    User getUser(Long id);

    void addUser(User user);

    void updateUser(User user);

    void deleteUser(Long id);
}

Guess you like

Origin blog.csdn.net/mu_wind/article/details/100034561
Recommended