Spring integration Mybatis plus

Posted May 26, 20205 min read

The former has become the specification of Spring Data, and is known for its minimalist and fully automatic object mapping. The latter is a semi-automated ORM framework. SQL is stored independently in XML files, which improves the degree of freedom and facilitates DBA Proofreading and subsequent SQL optimization

Since Mybatis plus is completely based on Mybatis, and absorbs some of the advantages of HIbernate, providing integrated CRUD, basically now in development, Mybatis Plus is used to replace the native Mybatis framework

Knock on the blackboard:MybatisPlus cannot be used simultaneously with Mybatis

Use process(three steps)

  1. Add Maven dependencies

  2. MyBatisPlus configuration

  3. Write 3 kinds of files(can use plug-in to generate, Idea Mybatis generater)

    • Entity
    • Dao layer interface Mapper
    • Sql statement in Xml file

The first step is to add Maven dependencies

<dependency>
    <groupId> com.baomidou </groupId>
    <artifactId> mybatisplus-spring-boot-starter </artifactId>
</dependency>
<dependency>
    <groupId> com.baomidou </groupId>
    <artifactId> mybatis-plus </artifactId>
</dependency>
<dependency>
    <groupId> mysql </groupId>
    <artifactId> mysql-connector-java </artifactId>
</dependency>

The second step is to configure Mybatis Plus in application.yml

If you use the properties configuration file, you can convert the yml file at http://www.toyaml.com/index.html

Focus !!!

The xml file of the first line is scanned.The xml file here is stored in the mapper path under resource(my path is resource/mapper/xx module/xxx.xml)
The second line of entity scanning !!! To configure according to your own entity directory, modify the typeAliasesPackage according to your entity class path, or use my modular project path(project root directory/modules/xx module/entity/xxx .class)

mybatis-plus:
  mapper-locations:classpath:mapper/**/*. xml #__Mapper path corresponding to the third step__
  #Entity scanning, multiple packages are separated by comma or semicolon
  typeAliasesPackage:io.renren.modules. *. entity #__ corresponds to the entity path of the third step __
  global-config:
    #Primary key type 0:"Database ID increment", 1:"User input ID", 2:"Global unique ID(number type unique ID)", 3:"Global unique ID UUID";
    id-type:0
    #Field strategy 0:"ignore judgment", 1:"non-NULL judgment"), 2:"non-empty judgment"
    field-strategy:2
    # Camel underline conversion
    db-column-underline:true
    #Refresh the mapper debugging artifact
    refresh-mapper:true
    #Database underline conversion
    # capital-mode:true
    #Serial interface implementation class configuration
    # key-generator:com.baomidou.springboot.xxx
    #Logical deletion configuration
    logic-delete-value:-1
    logic-not-delete-value:0
    #Custom fill strategy interface implementation
    # meta-object-handler:com.baomidou.springboot.xxx
    #Custom SQL injector
    sql-injector:com.baomidou.mybatisplus.mapper.LogicSqlInjector
  configuration:
    map-underscore-to-camel-case:true
    cache-enabled:false
    call-setters-on-nulls:true

Without adding mysq data source, add the following configuration

spring:
    datasource:
        continue-on-error:false
        driver-class-name:com.mysql.jdbc.Driver
        username:root ## Modify according to your MySQL username
        url:jdbc:mysql://127.0.0.1:3306/renren_test ## Modify according to your own MySQL IP and port
        password:root ## Modify according to your MySQL password

The third step into the topic

The previous steps are the configuration and management of Mybatis, the following is the real business code
  1. entity

The file is placed in the entity directory(to correspond to the physical scanning path of the second step, ignore it and go back to the second step carefully)

@TableName("sword")
public class Sword {
    @TableId
    private Long id;
    private String name;

}

Before using JPA, you may run directly and find that the table is not built in the database.Because Mybatis does not support automatic creation of tables based on the entity class, you need to build the table yourself.If you want to introduce this function, you can introduce JPA and only use JPA The automatic table creation function of this article, for the sake of simplicity and clarity, you can check my other article [Mybatis joined the automatic table creation function of JPA]

  1. mapper placed in Dao directory

    @Repository
    @Mapper
    public interface SwordMapper {

     Sword selectSword(Pagination page, String id);
     void insertSword(
             @Param("name") String name
    );

    }

  2. xml(to correspond to the mapper scanning path of the second step, ignore it and go back to the second step carefully)

    <! DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0 //EN" " http://mybatis.org/dtd/mybatis-3-mapper.dtd">

     <select id = "selectSword" resultType = "io.renren.modules.test.entity.Sword">
        select * from sword limit 1
     </select>
     <insert id = "insertSword">
         insert into sword(name) values  (# {name})
     </insert>

The file introduction method of Mybatis framework:

  • The entity is searched through the configuration typeAliasesPackage in the second step, or it can be searched through annotations
  • Mybatis xml corresponds to mapper, mapper provides the interface of java layer, xml saves the corresponding sql statement
  • xml was discovered by Mybatis in the configuration of the second step, and the corresponding Mapper file was associated in the xml by namespace

Last step test

Implement the Restful interface SwordController.class in the Controller file

@RestController
@RequestMapping
public SwordController {
    @Autowired //Automatic injection of mapper
    private SwordMapper swordMapper;

    @GetMapping("sword")
    public sword(UserEntity userEntity) {
        Sword sword1 = new Sword();
        sword1.setName("This is a sword");
        Sword sword = swordMapper.selectSword("1");
        return sword;
    }
}

Visit 127.0.0.1:8080/demo/sword

You're done!

postscript

As you may see in other blogs, there are many using sqlsession or SqlSessionFactoryBean to load Mybatis configuration files, I do n t have sqlsession here, and some people are often confused. Here is an explanation. In native mybatis, sqlsession can Created by SqlSessionFactory; in mybatis-spring, it needs to be created by SqlSessionFactoryBean and passed into datasource.
like this

<bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
      <property name = "configLocation">
          <value> classpath:mybatis/mapper.xml </value>
      </property>
      <property name = "dataSource" ref = "dataSource" />
</bean>

But in Springboot, mybatis-spring-boot supports the automatic creation and registration of SqlSessionFactoryBean, so the configuration of sqlsession is not required. Thanks Springboot.