整合 spring-boot 和 mybatis-plus 进行 Api 开发

使用 idea 社区版作为开发工具,gradle 作为构建工具

主要配置: 首先使用 SpringBoot 初始化项目进行项目模版配置,选择 web ,mysql,lombok 即可

build.gradle 配置

plugins {
  id 'org.springframework.boot' version '2.1.6.RELEASE'
  id 'java'
  id 'war'
}

apply plugin: 'io.spring.dependency-management'

group = 'io.github.joy.fxz'
version = '0.0.2'
sourceCompatibility = '1.8'

repositories {
  mavenCentral()
}

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-web'
  // 无需添加mybatis的依赖,防止与mybatis-plus整合的版本不一致
  implementation 'com.baomidou:mybatis-plus-boot-starter:3.1.2'
  // 使用p6spy查看生成的带有赋值参数的SQL语句
  implementation 'p6spy:p6spy:3.8.3'
  compileOnly 'org.projectlombok:lombok'
  runtimeOnly 'mysql:mysql-connector-java'
  annotationProcessor 'org.projectlombok:lombok'
  providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}

之后使用 IDEA 导入该 gradle 项目

注意: 由于 lombok 需要使用 annotationProcessor 进行代码生成操作,故而需要 IDEA 开启 annotation processor .

spring boot 的 application.properties 配置文件:

# spring数据源配置,可以使用原始mysql数据源;如果要使用P6SPY则必须使用P6SPY的代理Jdbc驱动程序
# spring.datasource.url= jdbc:mysql://localhost:3306/test
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.url = jdbc:p6spy:mysql://localhost:3306/test?useSSL=false
spring.datasource.username= root
spring.datasource.password=

# mybatis.type-aliases-package=io.github.joy.fxz.entity
# mybatis.mapperLocations=classpath:templates/mappers/*Mapper.xml
# 注意,使用mybatis-plus无需配置上面的mybatis的配置项,而是需要配置mybatis-plus的mapper-locations
# 同时,对于gradle工程,请将xml等配置资源文件放置在 src/resources 下面,不要放在src/java下面。放在src/java下面将不会找到资源配置文件。
mybatis-plus.mapper-locations=classpath:/mappers/*Mapper.xml

# 设置日志的级别
logging.level.io.github.joy.fxz=debug

数据库使用 mysql 8.0.17 ,有表 hotel_info:

CREATE TABLE `hotel_info` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(80) COLLATE utf8mb4_general_ci NOT NULL,
  `address` varchar(255) COLLATE utf8mb4_general_ci NOT NULL,
  `phone` varchar(30) COLLATE utf8mb4_general_ci NOT NULL,
  `create_time` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='酒店信息表';

spring 启动主程序:

package io.github.joy.fxz;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@MapperScan("io.github.joy.fxz.mapper")

public class FxzSpringMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(FxzSpringMybatisApplication.class, args);
    }
    /**
     * 分页插件,使用自动的分页插件,这样分页查询时只需要写SELECT语句即可
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setLimit(20); // 设置默认的每页数据条数
        return paginationInterceptor;
    }
}

实体类 Hotel:

package io.github.joy.fxz.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.time.LocalDateTime;

@Data
@TableName("HOTEL_INFO")
public class Hotel {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private String address="";
    private String phone="";
    private LocalDateTime createTime=LocalDateTime.now();
}

mapper 类:

package io.github.joy.fxz.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.joy.fxz.entity.Hotel;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface HotelMapper extends BaseMapper<Hotel> {
    IPage<Hotel> paginate(Page page);
}

mapper 对应的 XML 配置:

<?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="io.github.joy.fxz.mapper.HotelMapper">
    <select id="paginate" resultType="io.github.joy.fxz.entity.Hotel">
        SELECT * FROM HOTEL_INFO
    </select>
</mapper>

service 类:

package io.github.joy.fxz.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.joy.fxz.entity.Hotel;
import io.github.joy.fxz.mapper.HotelMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class HotelService {
    // 由于 HotelMapper只是增加了 @Mapper 这个由 mybatis 提供的注解,因此不能使用Autowired注解自动注入
    @Resource
    private HotelMapper hotelMapper;

    public Hotel current() {
        return hotelMapper.selectById(1L);
    }

    public void add(Hotel hotel) {
        hotelMapper.insert(hotel);
    }

    public IPage<Hotel> paginate(Integer page){
        page = page==null?1:Math.abs(page);
        Page<Hotel> pageable = new Page<>();
        pageable.setCurrent(page);
        pageable.setSize(20);
        return hotelMapper.paginate(pageable);
    }
}

controller 类:

package io.github.joy.fxz.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.joy.fxz.entity.Hotel;
import io.github.joy.fxz.service.HotelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class HotelController {
    @Autowired
    private HotelService hotelService;

    @GetMapping("/hotels/current")
    public Hotel current() {
        return hotelService.current();
    }

    @GetMapping("/hotels/add")
    public Hotel add(String name) {
        Hotel hotel = new Hotel();
        hotel.setName(name);
        hotelService.add(hotel);
        return hotel;
    }

    @GetMapping("/hotels")
    public IPage<Hotel> paginate(Integer page){
        return hotelService.paginate(page);
    }
}

测试,运行启动主程序,使用浏览器访问 http://localhost:8080/api/hotels 可以观察到 控制台输出正确的带有赋值参数的 SQL 语句:

p6spy : | 0 ms | SELECT * FROM HOTEL_INFO LIMIT 0,20

定制 jar 文件或 war 文件的 gradle 配置 build.gradle:

// 使用 gradle 5.5.1 进行构建
plugins {
    id 'org.springframework.boot' version '2.1.6.RELEASE'
    id 'java'
    id 'war'
}

apply plugin: 'io.spring.dependency-management'

group = 'io.github.joy.fxz'
version = '0.0.2'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

war {
    enabled = true  // 开启 普通的 war 任务,减小打包成为war的体积
    archiveFileName="fxz-spring-mybatis.war"
}

// 可以独立执行的 war 包
bootWar {
    excludeDevtools = true // 不要打包springboot开发工具
    archiveFileName="fxz-spring-mybatis-boot.war"
}

// 将lib文件夹外置
bootJar {
    archiveFileName="fxz-spring-mybatis-boot.jar"
    excludes = ["*.jar"]
}

// 只打包自己项目的类
jar {
    enabled = true  // 开启 jar 任务
    archiveFileName="fxz-spring-mybatis.jar"
    // 配置文件外置
    exclude("/*.properties")
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'com.baomidou:mybatis-plus-boot-starter:3.1.2'
    implementation 'p6spy:p6spy:3.8.3'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'mysql:mysql-connector-java'
    annotationProcessor 'org.projectlombok:lombok'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}