美文网首页
[Mybatis-Plus] Springboot2集成Myba

[Mybatis-Plus] Springboot2集成Myba

作者: 后端技术学习分享 | 来源:发表于2019-01-02 18:22 被阅读24次

环境

  • Springboot:2.1.1.RELEASE
  • Mybatis-plus:2.2.0
  • 依赖
<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatisplus.version}</version>
        </dependency>
  • application.yml内关于plus的配置(参考,不一定需要)
mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  typeAliasesPackage: com.lvjian.jiyu.entity
  global-config:
    id-type: 2
    db-column-underline: true
    refresh-mapper: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true

集成

编写配置类

MybatisPlusConfig.java

package com.xxx.xxx.config;

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@Configuration
@MapperScan("com.xxx.xxx.mapper")
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}
在通用CRUD方法中使用

适用于不自己写sql语句,直接使用mybatis自带的方法,一般在service层使用

// pageNum是页码,pageSize是该页码内包含的记录数
Page pageBean = new Page<Tenant>(pageNum, pageSize);
List<User> users = userMapper.selectPage(pageBean);
pageBean.setRecords(users);
在自己编写sql的场景里使用

有些时候业务比较复杂,需要在mapper的xml文件里自己编写xml文件。

  1. 需要编写xml的mapper方法为
List<User> getUserListByName(@Param("page") Pagination page, @Param("name") String name);

注意Pagination必须有,且最好在第一个参数

  1. service层调用mapper
// pageNum是页码,pageSize是该页码内包含的记录数
Page pageBean = new Page<Tenant>(pageNum, pageSize);
List<User> users = userMapper.getUserListByName(pageBean,"spz");
pageBean.setRecords(users);
返回举例(JSON)

total 为总记录数,pages是总页数,current是当前页码

{
        "total": 2,
        "size": 1,
        "pages": 2,
        "current": 1,
        "records": [
            {
                "modifiedTime": 1546421510000,
                "rentFlag": 0,
                "createTime": 1545358162000,
                "sex": 1,
                "idCardBackPath": "",
                "name": "张三"
            }
        ]
    }

相关文章

网友评论

      本文标题:[Mybatis-Plus] Springboot2集成Myba

      本文链接:https://www.haomeiwen.com/subject/vlqtrqtx.html