mybatis integration SpringBoot (caching)

With mybatis company to integrate our tools so that we do not have to go as before We are here to configure the data source can only rely on the introduction of:

We first create a simple database

create database springbootmapper;

CREATE TABLE `user` (
  `id` int(16) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(16) NOT NULL,
  `age` int(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

Casually insert a few data:
Here Insert Picture DescriptionProject Structure
Here Insert Picture Description

In the introduction rely create works →

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

    <groupId>com.cs</groupId>
    <artifactId>springBoot_Mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-base</artifactId>
            <version>1.1.5</version>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-core</artifactId>
            <version>1.1.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-extra</artifactId>
            <version>1.1.5</version>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring</artifactId>
            <version>1.1.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Create a profile:
application.yml

server:
  port: 8333  #端口号

mybatis:
  type-aliases-package: com.cs.dto.UserDto  #对应的实体类
  configuration:
    map-underscore-to-camel-case: true
  mapper-locations: mappers/*.xml #如果还想用之前的mapper.xml写sql语句也可以放在这里
spring:
  application:
    name: myTest  
  datasource: #数据源
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/springbootmapper?characterEncoding=utf8&amp;useSSL=false
      username: root
      password: root

Create an entity class database table corresponding to the (object-relational mapping the ORM)
UserDTO .java

package com.cs.demo.dto;

import lombok.Data;
import tk.mybatis.mapper.annotation.KeySql;
import javax.persistence.Id;
import javax.persistence.Table;

@Data  //lombok注解  自动有 get set 方法
@Table(name = "user")  //配置表名
public class UserDto {
    @Id //设置主键
    @KeySql(useGeneratedKeys = true) //允许JDBC支持自动生成主键
    private Integer id;
    private String name;
    private Integer age;
}

Create a persistence layer (database layer) we use here is the abstract class mybatis provided us, which comes with curd operations (referred to as the Universal Mapper)
MyMapper .java

package com.cs.demo.mapper;

import com.cs.demo.dto.UserDto;
import tk.mybatis.mapper.common.Mapper;

public interface MyMapper extends Mapper<UserDto> {
}

Create a transaction layer
MyService .java

package com.cs.demo.service;

import com.cs.demo.dto.UserDto;
import com.cs.demo.mapper.MyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component //注入到spring 容器里
public class MyService {

    @Autowired //从spring容器实例化对象
    private MyMapper myMapper;

    public List<UserDto> findAll() {
        List<UserDto> userDtos = myMapper.selectAll();
        return userDtos;
    }
}

Create a presentation layer:
MyController .java

package com.cs.demo.controller;
import com.cs.demo.dto.UserDto;
import com.cs.demo.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@RestController
public class MyController {

    @Autowired
    private MyService myService;

    @GetMapping("findAll")
    public List<UserDto> findAll(){
        List<UserDto> all = myService.findAll();
        return all;
    }
}

Create Launcher:

package com.cs;
import tk.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.cs.demo.mapper") //扫描我们的只定义mapper
public class SpringBootMybatis {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMybatis.class,args);
    }
}

The results:
Here Insert Picture Descriptionyou can see the success of our operations.

Then his principle of what is it, let's look at before drawing mybatis operation
Here Insert Picture DescriptionHere Insert Picture Descriptionwe through the factory model created a sqlSession, then dynamic proxy agent out our our connection object through sqlSession, that is our approach to query a database, dynamic analysis xml file, we assembled a dynamic sql statement, and then send to mysql sql statement by jdbc protocol, in order to prevent the problem here injection sql, mybatis the sql sent twice, the first time: send the whole statement, such as select * from user where id = second:?. it values at 1 id to send sql, mysql finally returned to our back-end results.

Mybatis its integrated spring is the same but he is ahead of the previously difficult for us to engage in reverse engineering sql staged a unified tools, then we just need to call its tools can be.

Cache

Before we so need to set the cache settings

  1. A cache: a HashMap based PerpetualCache local cache, which stores a scope of Session, Session after the flush or close, all of the Cache will be cleared in the Session.
  2. And a secondary cache which caches the same mechanism, but also using default PerpetualCache, HashMap stored, it is stored in a different scope as Mapper (Namespace), and may be custom storage source, such as Ehcache. Scope of namespance refers to all of the select operation result namespance corresponding configuration file are cached, the cache can be shared between such two different threads. Start secondary cache: In mapper configuration file:
    You can set the cache secondary cache the returned object policy: When readOnly = "true", represents the secondary cache to return
    back to all callers the same object instance cache, cache instance the caller can get the update, but this may cause other callers appear several
    cases of inconsistent data (since all the caller called is the same instance). When readOnly = "false", is returned to the caller of the total secondary cache buffer
    copy storage object, i.e. different caller is acquired different cache object instances, modifications to the caller so that each cached object will not affect to the other
    caller, that is safe, so the default is readOnly = "false";

The schematic diagram (own painting)
Here Insert Picture Description

  • Level cache is based SQLSession cache, cache contents can not span SQLSession. Maintained automatically by mybatis. Buffer area between the different sqlsession is not affected by each other.
  • Secondary cache based on cache map file (namespace), is larger than the range of cache a cache, the content can access different SQLSession secondary cache. What data into the secondary cache needs its own designated. (Common, do not often modified, such as: classification, department)
  • Here Insert Picture DescriptionWe must first manually open mybatis L2 cache.

Secondary cache provided in the switch config.xml, also open in the secondary cache specific mapper.xml
. 1.

<settings>
    <!--开启二级缓存-->
    <setting name="cacheEnabled" value="true"/>       
</settings>

2. The need to javapojo class map to achieve serialization (this is our generation through reverse engineering before the auxiliary class)

      class User implements Serializable{}

3.

About cache attributes:

eviction: represents the cache recovery strategy, MyBatis currently offers the following strategies.

(1) LRU (Least Recently Used), the least recently used, most of the objects do not have time

(2) FIFO (First In First Out), FIFO, objects in the order they entered the cache removed

(3) SOFT, soft references, the garbage collector remove the object based on the status rules and soft references

(4) WEAK, weak references, more aggressive removal of objects based on the garbage collector state and rules of Weak References. Here is LRU,
remove unused for the longest time image

flushInterval: refresh interval time, in milliseconds, the configuration here is 100 seconds to refresh, if you do not configure it, then when
the time SQL will be executed to refresh the cache.

size: the number of references, a positive integer representing the maximum number of cached objects can be stored, should not be set too high. Set over the General Assembly cause a memory overflow.
Here is the 1024 configuration objects

readOnly: read-only, meaning that the cached data can only be read but not modify, the benefits of this set up is that we can quickly read cache, the disadvantage is we have no
way to change the cache, he's default value is false, it does not allow us to modify

Operation process:

sqlsession1 querying user id information is 1, then the query, the query to the data stored in the secondary cache.

If sqlsession3 to perform the same sql mapper, commit the execution, clears the data in the secondary cache area in the mapper

sqlsession2 to query the user id information is 1, the cache to find whether there is a cache, if there is to take data directly from the cache

Disable secondary cache:

May be provided in the statement useCache = false, the secondary cache disable current select statement is true by default

In the actual development, for every query requires the latest data sql, to set useCache = "false", disable the secondary cache
flushCache Tags: flush the cache (to clear the cache)

After performing the commit operation generally needs to flush the cache, flushCache = "true indicates refresh cache to avoid dirty reads
secondary cache scenarios

For access to multiple query request and the query results to the user less demanding real-time, can be mybatis secondary cache, reducing the amount of database access, faster access, such as a telephone bill inquiry

The requirements set corresponding flushInterval: refresh interval, such as thirty minutes, 24 hours and so on. . .
Secondary cache limitations:

mybatis secondary cache data cache for fine-grained level of implementation is not good, such as the following requirements: information on the goods cache, since the goods large query access information, but requires the user to query every time the latest product information at this time if use mybatis secondary cache can not be achieved only flushes the cache information of the merchandise when a product changes without refreshing the information of other commodities, because the secondary cache area mybaits to mapper units of division, when a commodity information will change all all product information data cache emptied. The need to solve such problems in the business layer according to the needs of targeted cache data.

So how do you set up the secondary cache in our mybatis integration SpringBoot

Mybatis Configuration

  • # The global mapper to enable or disable the cache.
    mybatis.configuration.cache-enabled = true
  • # Globally enable or disable lazy loading. When disabled, all associations will be eagerly loaded.
    mybatis.configuration.lazy-loading-enabled = true
  • # When enabled, there is a delay loading the object properties will be fully loaded when any property is called. Otherwise, each property will be loaded on demand.
    mybatis.configuration.aggressive-lazy-loading = true
  • # Sql returns whether to allow a single plurality of data sets (depending on the drive compatibility) default: to true
    mybatis.configuration.multiple-Result-sets to true-Enabled =
  • Can # alias (depending on the drive compatibility) column default: to true
    mybatis.configuration.use to true-column-label =
  • # JDBC allows generating primary keys. You need to drive support. If set to a true, this setting will be forced to use to generate the primary key, there are some drivers are not compatible, but can still perform. default: to false
    mybatis.configuration.use-Generated-Keys to true =
  • MyBatis # Specify how to automatically map data base table columns NONE: no hint \ u3000PARTIAL: Part FULL: All
    mybatis.configuration.auto-mapping-behavior = partial
  • # This is the default execution type (SIMPLE: Simple; REUSE: actuator may reuse prepared statements statements; BATCH: The actuator can repeat the statements and batch updates)
    mybatis.configuration.default-Executor of the type-the Simple =
  • # Use hump nomenclature conversion field.
    mybatis.configuration.map-underscore-to-camel- case = true
  • # Set the local cache range session: the data will be shared statement: statement range (this would not have shared data) defalut: the session
    mybatis.configuration.local-Cache-scope the session =
  • # Set the JDBC type but is empty, some drivers to the specified value, default: OTHER, do not need to specify the type when inserting nulls
    mybatis.configuration.jdbc-type-for-null = null
  • # If the data field is empty, the display field is omitted, by adding the configuration file, the data specified query is empty or null.
    mybatis.configuration.call-setters-on-nulls = true

Then we only need to add such a passage

mybatis:
  type-aliases-package: com.cs.dto.UserDto  #对应的实体类
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true #开启二级缓存
  mapper-locations: mappers/*.xml #如果还想用之前的mapper.xml写sql语句也可以放在这里
Published 69 original articles · won praise 6 · views 2499

Guess you like

Origin blog.csdn.net/qq_40539437/article/details/104012551