EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程

EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程

    • 新建工程
    • 添加Spring Boot和日志的配置文件
    • 配置Easycode template
    • 配置文件源代码
    • 配置easy code 数据源
    • 测试
    • GitHub源码地址
    • 总结

新建工程

新建一个Module
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第1张图片
选择maven工程,并选择jdk版本为1.8,单击next,直接进入下一步

EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第2张图片
这里命名随便写,但是为了减少出错,第一次可以参考我的写法,当然读者也可以自由发挥。
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第3张图片
命名好之后,单击next。
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第4张图片
单击finish完成工程的创建,新建好的文件结构如下图所示:
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第5张图片

修改pom文件,添加需要的pom文件。废话不多说,直接上源码。
pom.xml


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.2.5.RELEASEversion>
        <relativePath/> 
    parent>


    <groupId>com.njust.easymappergroupId>
    <artifactId>easymapperartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <java.version>1.8java.version>
        <swagger.version>2.9.2swagger.version>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-starter-loggingartifactId>
                exclusion>
            exclusions>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-starter-loggingartifactId>
                exclusion>
            exclusions>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.0version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.9version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.47version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.41version>
        dependency>
        
        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.3.1version>
        dependency>
        
        <dependency>
            <groupId>org.mybatis.generatorgroupId>
            <artifactId>mybatis-generator-coreartifactId>
            <version>1.3.2version>
            <scope>compilescope>
            <optional>trueoptional>
        dependency>
        
        <dependency>
            <groupId>tk.mybatisgroupId>
            <artifactId>mapper-spring-boot-starterartifactId>
            <version>1.2.4version>
        dependency>
        
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelper-spring-boot-starterartifactId>
            <version>1.2.3version>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-log4jartifactId>
            <version>1.3.3.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>${swagger.version}version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>${swagger.version}version>
        dependency>

    dependencies>
    
    <build>
        <plugins>
            
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
            
            <plugin>
                <groupId>org.mybatis.generatorgroupId>
                <artifactId>mybatis-generator-maven-pluginartifactId>
                <version>1.3.2version>
                <configuration>
                    <verbose>trueverbose>
                    <overwrite>trueoverwrite>
                configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysqlgroupId>
                        <artifactId>mysql-connector-javaartifactId>
                        <version>5.1.29version>
                    dependency>
                    <dependency>
                        <groupId>tk.mybatisgroupId>
                        <artifactId>mapperartifactId>
                        <version>4.0.0version>
                    dependency>
                dependencies>
            plugin>
        plugins>
    build>


project>

添加Spring Boot和日志的配置文件

新建项目包
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第6张图片
application.yml

server:
  port: 8082

logging:
  config: classpath:log4j.properties
  level:
    dao: debug
    org:
      mybatis: debug
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8

  jackson:
    default-property-inclusion: non_null

# 指定数据库中表生成实体的路径
mybatis:
  type-aliases-package: com.njust.easymapper.entity
  mapper-locations: classpath:mapper/*.xml
  configuration:
    #    输出sql日志信息
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl


#pagehelper
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params:
    count: countSql


log4j.properties

#Console Log
log4j.rootLogger=INFO,console,debug,info,warn,error

LOG_PATTERN=[%d{yyyy-MM-dd HH:mm:ss.SSS}] boot%X{context} - %5p [%t] --- %c{1}: %m%n

#A1--Print log to Console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=${LOG_PATTERN}

log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.Threshold=INFO
log4j.appender.info.File=${LOG_PATH}/${LOG_FILE}_info.log
log4j.appender.info.DatePattern='.'yyyy-MM-dd
log4j.appender.info.layout = org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=${LOG_PATTERN}

log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.Threshold=ERROR
log4j.appender.error.File=${LOG_PATH}/${LOG_FILE}_error.log
log4j.appender.error.DatePattern='.'yyyy-MM-dd
log4j.appender.error.layout = org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=${LOG_PATTERN}


log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
log4j.appender.debug.Threshold=DEBUG
log4j.appender.debug.File=${LOG_PATH}/${LOG_FILE}_debug.log
log4j.appender.debug.DatePattern='.'yyyy-MM-dd
log4j.appender.debug.layout = org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern=${LOG_PATTERN}

log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender
log4j.appender.warn.Threshold=WARN
log4j.appender.warn.File=${LOG_PATH}/${LOG_FILE}_warn.log
log4j.appender.warn.DatePattern='.'yyyy-MM-dd
log4j.appender.warn.layout = org.apache.log4j.PatternLayout
log4j.appender.warn.layout.ConversionPattern=${LOG_PATTERN}

配置Easycode template

选择file->settings
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第7张图片

选择File | Settings | Other Settings | Easy Code | Template Setting。
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第8张图片
点击添加按钮,并命名为njust(名称可以随便取),如下图所示。
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第9张图片

按照下图所示新建一个个配置文件。
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第10张图片

配置文件源代码

entity.java


##引入宏定义
$!define

##使用宏定义设置回调(保存位置与文件后缀)
#save("/entity", ".java")

##使用宏定义设置包后缀
#setPackageSuffix("entity")

##使用全局变量实现默认包导入
$!autoImport
import java.io.Serializable;
import io.swagger.annotations.*;
import lombok.Data;
import javax.persistence.*;

##使用宏定义实现类注释信息
#tableComment("实体类")
@Data
@ApiModel("$tableInfo.comment")
public class $!{tableInfo.name} implements Serializable {
    private static final long serialVersionUID = $!tool.serial();

#foreach($column in $tableInfo.pkColumn )
    #if(${column.comment})/**
    * ${column.comment}
    */
    #end
@Id
    private $!{tool.getClsNameByFullName($column.type)} $!{column.name};
#end

#foreach($column in $tableInfo.otherColumn )
    #if(${column.comment})/**
    * ${column.comment}
    */
    #end
private $!{tool.getClsNameByFullName($column.type)} $!{column.name};

#end

}

IBaseMapper.java注意这里的Mapper不能放在com.njust.easymapper.mapper路径下面。因为spring扫描的时候,会找对应的mapper.xml,很明显这个基类是没有 的,所以会报错。但是我们需要封装,所以就把她放到base包下面,避免spring扫描。

##设置回调
$!callback.setFileName("IBaseMapper.java")
$!callback.setSavePath($tool.append($tableInfo.savePath, "/base/mapper"))
##使用宏定义设置回调(保存位置与文件后缀)
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}base.mapper;


import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;


/**
 * $!{tableInfo.comment}($!{tableInfo.name})抽象表数据库访问层
 *
 * @author $!author
 * @since $!time.currTime()
 */
public interface IBaseMapper<T> extends Mapper<T>, MySqlMapper<T> {
}

dao.java

##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "Mapper"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/mapper"))

##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())
    #set($pk = $tableInfo.pkColumn.get(0))
#end

#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}mapper;

import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.base.mapper.IBaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;


/**
 * $!{tableInfo.comment}($!{tableInfo.name})表数据库访问层
 *
 * @author $!author
 * @since $!time.currTime()
 */
public interface $!{tableName}  extends IBaseMapper<$!{tableInfo.name}> {

    /**
     * 通过ID查询单条数据
     *
     * @param $!pk.name 主键
     * @return 实例对象
     */
    $!{tableInfo.name} queryById($!pk.shortType $!pk.name);

    /**
     * 查询指定行数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    List<$!{tableInfo.name}> queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit);


    /**
     * 通过实体作为筛选条件查询
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象
     * @return 对象列表
     */
    List<$!{tableInfo.name}> queryAll($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));

    /**
     * 新增数据
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象
     * @return 影响行数
     */
    int insert($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));

    /**
     * 修改数据
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象
     * @return 影响行数
     */
    int update($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));

    /**
     * 通过主键删除数据
     *
     * @param $!pk.name 主键
     * @return 影响行数
     */
    int deleteById($!pk.shortType $!pk.name);

}

service.java

##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "Service"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/service"))

##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())
    #set($pk = $tableInfo.pkColumn.get(0))
#end

#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}service;

import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import java.util.List;

/**
 * $!{tableInfo.comment}($!{tableInfo.name})表服务接口
 *
 * @author $!author
 * @since $!time.currTime()
 */
public interface $!{tableName} {

    /**
     * 通过ID查询单条数据
     *
     * @param $!pk.name 主键
     * @return 实例对象
     */
    $!{tableInfo.name} queryById($!pk.shortType $!pk.name);

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    List<$!{tableInfo.name}> queryAllByLimit(Integer offset, Integer limit);

    /**
     * 新增数据
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象
     * @return 实例对象
     */
    $!{tableInfo.name} insert($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));

    /**
     * 修改数据
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象
     * @return 实例对象
     */
    $!{tableInfo.name} update($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));

    /**
     * 通过主键删除数据
     *
     * @param $!pk.name 主键
     * @return 是否成功
     */
    boolean deleteById($!pk.shortType $!pk.name);

}

serviceImpl.java

##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "ServiceImpl"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/service/impl"))

##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())
    #set($pk = $tableInfo.pkColumn.get(0))
#end

#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}service.impl;

import $!{tableInfo.savePackageName}.base.service.BaseService;
import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.mapper.$!{tableInfo.name}Mapper;
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * $!{tableInfo.comment}($!{tableInfo.name})表服务实现类
 *
 * @author $!author
 * @since $!time.currTime()
 */
@Service
public class $!{tableName} implements $!{tableInfo.name}Service {
    @Resource
    private $!{tableInfo.name}Mapper $!tool.firstLowerCase($!{tableInfo.name})Mapper;

    /**
     * 通过ID查询单条数据
     *
     * @param $!pk.name 主键
     * @return 实例对象
     */
    @Override
    public $!{tableInfo.name} queryById($!pk.shortType $!pk.name) {
        return BaseService.queryById($!pk.name, $!{tool.firstLowerCase($!{tableInfo.name})}Mapper);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<$!{tableInfo.name}> queryAllByLimit(Integer offset, Integer limit) {
        return BaseService.queryAllByLimit(offset, limit,new User(),$!{tool.firstLowerCase($!{tableInfo.name})}Mapper);
    }

    /**
     * 新增数据
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象
     * @return 实例对象
     */
    @Override
    public $!{tableInfo.name} insert($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name})) {
        return BaseService.insert(user,$!{tool.firstLowerCase($!{tableInfo.name})}Mapper);
    }

    /**
     * 修改数据
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 实例对象
     * @return 实例对象
     */
    @Override
    public $!{tableInfo.name} update($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name})) {
        return BaseService.update(user, $!{tool.firstLowerCase($!{tableInfo.name})}Mapper);
    }

    /**
     * 通过主键删除数据
     *
     * @param $!pk.name 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById($!pk.shortType $!pk.name) {
        return BaseService.deleteById($!pk.name, $!{tool.firstLowerCase($!{tableInfo.name})}Mapper);
    }
}

controller.java

##定义初始变量
#set($tableName = $tool.append($tableInfo.name, "Controller"))
##设置回调
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/controller"))
##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())
    #set($pk = $tableInfo.pkColumn.get(0))
#end

#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}controller;

import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import $!{tableInfo.savePackageName}.http.HttpResult;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * $!{tableInfo.comment}($!{tableInfo.name})表控制层
 *
 * @author $!author
 * @since $!time.currTime()
 */
 @Api(tags = "$!{tableInfo.comment}($!{tableInfo.name})")
@RestController
@RequestMapping("$!tool.firstLowerCase($tableInfo.name)")
public class $!{tableName} {
    /**
     * 服务对象
     */
    @Resource
    private $!{tableInfo.name}Service $!tool.firstLowerCase($tableInfo.name)Service;


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "根据id查询 $!{tableInfo.comment}")
    @GetMapping("selectOne")
    public HttpResult selectOne($!pk.shortType id) {
        return HttpResult.ok($!{tool.firstLowerCase($tableInfo.name)}Service.queryById(id));
    }

    @PostMapping(value = "/save")
    public HttpResult save(@RequestBody $!{tableInfo.name} user) {
        return HttpResult.ok($!{tool.firstLowerCase($tableInfo.name)}Service.insert(user));
    }

    @DeleteMapping(value = "/deleteById")
    public HttpResult deleteById(@RequestParam $!pk.shortType id) {
        return HttpResult.ok($!{tool.firstLowerCase($tableInfo.name)}Service.deleteById(id));
    }

    @GetMapping(value = "/findPage")
    public HttpResult findPage(@RequestParam(value = "offset", required = false) Integer offset, @RequestParam(value = "limit", required = false) Integer limit) {
        return HttpResult.ok($!{tool.firstLowerCase($tableInfo.name)}Service.queryAllByLimit(offset, limit));
    }

    @PutMapping(value = "/update")
    public HttpResult update(@RequestBody $!{tableInfo.name} user) {
        return HttpResult.ok($!{tool.firstLowerCase($tableInfo.name)}Service.update(user));
    }
}

mapper.xml

##引入mybatis支持
$!mybatisSupport

##设置保存名称与保存位置
$!callback.setFileName($tool.append($!{tableInfo.name}, "Mapper.xml"))
$!callback.setSavePath($tool.append($modulePath, "/src/main/resources/mapper"))

##拿到主键
#if(!$tableInfo.pkColumn.isEmpty())
    #set($pk = $tableInfo.pkColumn.get(0))
#end



<mapper namespace="$!{tableInfo.savePackageName}.mapper.$!{tableInfo.name}Mapper">

    <resultMap type="$!{tableInfo.savePackageName}.entity.$!{tableInfo.name}" id="$!{tableInfo.name}Map">
#foreach($column in $tableInfo.fullColumn)
        <result property="$!column.name" column="$!column.obj.name" jdbcType="$!column.ext.jdbcType"/>
#end
    resultMap>

    
    <select id="queryById" resultMap="$!{tableInfo.name}Map">
        select
          #allSqlColumn()

        from $!{tableInfo.obj.parent.name}.$!tableInfo.obj.name
        where $!pk.obj.name = #{$!pk.name}
    select>

    
    <select id="queryAllByLimit" resultMap="$!{tableInfo.name}Map">
        select
          #allSqlColumn()

        from $!{tableInfo.obj.parent.name}.$!tableInfo.obj.name
        limit #{offset}, #{limit}
    select>

    
    <select id="queryAll" resultMap="$!{tableInfo.name}Map">
        select
          #allSqlColumn()

        from $!{tableInfo.obj.parent.name}.$!tableInfo.obj.name
        <where>
#foreach($column in $tableInfo.fullColumn)
            
                and $!column.obj.name = #{$!column.name}
            if>
#end
        where>
    select>

    
    <insert id="insert" keyProperty="$!pk.name" useGeneratedKeys="true">
        insert into $!{tableInfo.obj.parent.name}.$!{tableInfo.obj.name}(#foreach($column in $tableInfo.otherColumn)$!column.obj.name#if($velocityHasNext), #end#end)
        values (#foreach($column in $tableInfo.otherColumn)#{$!{column.name}}#if($velocityHasNext), #end#end)
    insert>

    
    <update id="update">
        update $!{tableInfo.obj.parent.name}.$!{tableInfo.obj.name}
        <set>
#foreach($column in $tableInfo.otherColumn)
            
                $!column.obj.name = #{$!column.name},
            if>
#end
        set>
        where $!pk.obj.name = #{$!pk.name}
    update>

    
    <delete id="deleteById">
        delete from $!{tableInfo.obj.parent.name}.$!{tableInfo.obj.name} where $!pk.obj.name = #{$!pk.name}
    delete>

mapper>

chenApplication

##设置回调
$!callback.setFileName("ChenApplication.java")
$!callback.setSavePath($tableInfo.savePath)

#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName};

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import tk.mybatis.spring.annotation.MapperScan;

/**
 * 启动类
 *
 * @author $!author
 * @since $!time.currTime()
 */
@SpringBootApplication
@EnableSwagger2
@MapperScan("$!{tableInfo.savePackageName}.#{end}mapper")
public class ChenApplication {

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

}

这里有个主意的地方,引入的包是tk.mybatis.spring.annotation.MapperScan;。因为我们是使用通用的mapper,使用的是这个MapperScan。使用org.mybatis.spring.annotation.MapperScan;会报错。
baseMapperOP

##设置回调
$!callback.setFileName("BaseMapperOP.java")
$!callback.setSavePath($tool.append($tableInfo.savePath, "/base/mapper"))
##使用宏定义设置回调(保存位置与文件后缀)
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}base.mapper;


import $!{tableInfo.savePackageName}.base.mapper.IBaseMapper;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.annotations.Param;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 *  基类
 *
 * @author $!author
 * @since $!time.currTime()
 */
public class BaseMapperOP {
    public static final Integer DEFAULT_PAGE_SIZE = 10;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    public static <T> T queryById(Integer id, IBaseMapper<T> baseMapper) {
        return baseMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询指定行数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    public static <T> List<T> queryAllByLimit(Integer offset, Integer limit, T t, IBaseMapper<T> baseMapper) {
        //如果不传,则设置成默认值
        if (offset == null) {
            offset = 1;
        }
        if (limit == null) {
            limit = DEFAULT_PAGE_SIZE;
        }
        PageHelper.startPage(offset, limit);
        // 告诉系统查询那个类
        Example example = new Example(t.getClass());
        return baseMapper.selectByExample(example);
    }


    /**
     * 通过实体作为筛选条件查询
     *
     * @param t 实例对象
     * @return 对象列表
     */
    public static <T> List<T> queryAll(T t, IBaseMapper<T> baseMapper) {
        return queryAllByLimit(null, null, t, baseMapper);
    }

    /**
     * 新增数据
     *
     * @param t 实例对象
     * @return 影响行数
     */
    public static <T> int insert(T t, IBaseMapper<T> baseMapper) {
        return baseMapper.insertSelective(t);
    }

    /**
     * 修改数据 根据ID修改
     *
     * @param t 实例对象
     * @return 影响行数
     */
    public static <T> int update(T t, IBaseMapper<T> baseMapper) {
        return baseMapper.updateByPrimaryKeySelective(t);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 影响行数
     */
    public static <T> int deleteById(Integer id, IBaseMapper<T> baseMapper) {
        return baseMapper.deleteByPrimaryKey(id);
    }
}

baseService.java封装curd等基本操作。以后的代码也可以使用多态操作,选择性更多。

##设置回调
$!callback.setFileName("BaseService.java")
$!callback.setSavePath($tool.append($tableInfo.savePath, "/base/service"))
##使用宏定义设置回调(保存位置与文件后缀)
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}base.service;


import $!{tableInfo.savePackageName}.base.mapper.BaseMapperOP;
import $!{tableInfo.savePackageName}.base.mapper.IBaseMapper;
import java.util.List;

/**
 * 基类服务
 *
 * @author $!author
 * @since $!time.currTime()
 */
public class BaseService {

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    public static <T> T queryById(Integer id, IBaseMapper<T> baseMapper) {
        return BaseMapperOP.queryById(id, baseMapper);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    public static <T> List<T> queryAllByLimit(Integer offset, Integer limit, T t, IBaseMapper<T> baseMapper) {
        return BaseMapperOP.queryAllByLimit(offset, limit, t, baseMapper);
    }

    /**
     * 新增数据
     *
     * @param t 实例对象
     * @return 实例对象
     */
    public static <T> T insert(T t, IBaseMapper<T> baseMapper) {
        BaseMapperOP.insert(t, baseMapper);
        return t;
    }

    /**
     * 修改数据
     *
     * @param t 实例对象
     * @return 实例对象
     */
    public static <T> T update(T t, IBaseMapper<T> baseMapper) {
        BaseMapperOP.update(t, baseMapper);
        return t;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public static <T> boolean deleteById(Integer id, IBaseMapper<T> baseMapper) {
        return BaseMapperOP.deleteById(id, baseMapper) > 0;
    }
}



httpStatus

##设置回调
$!callback.setFileName("HttpStatus.java")
$!callback.setSavePath($tool.append($tableInfo.savePath, "/http"))
##使用宏定义设置回调(保存位置与文件后缀)
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}http;



/**
 * Http 状态
 *
 * @author $!author
 * @since $!time.currTime()
 */
public interface HttpStatus {
    // --- 1xx Informational ---

    /** {@code 100 Continue} (HTTP/1.1 - RFC 2616) */
    public static final int SC_CONTINUE = 100;
    /** {@code 101 Switching Protocols} (HTTP/1.1 - RFC 2616)*/
    public static final int SC_SWITCHING_PROTOCOLS = 101;
    /** {@code 102 Processing} (WebDAV - RFC 2518) */
    public static final int SC_PROCESSING = 102;

    // --- 2xx Success ---

    /** {@code 200 OK} (HTTP/1.0 - RFC 1945) */
    public static final int SC_OK = 200;
    /** {@code 201 Created} (HTTP/1.0 - RFC 1945) */
    public static final int SC_CREATED = 201;
    /** {@code 202 Accepted} (HTTP/1.0 - RFC 1945) */
    public static final int SC_ACCEPTED = 202;
    /** {@code 203 Non Authoritative Information} (HTTP/1.1 - RFC 2616) */
    public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
    /** {@code 204 No Content} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NO_CONTENT = 204;
    /** {@code 205 Reset Content} (HTTP/1.1 - RFC 2616) */
    public static final int SC_RESET_CONTENT = 205;
    /** {@code 206 Partial Content} (HTTP/1.1 - RFC 2616) */
    public static final int SC_PARTIAL_CONTENT = 206;
    /**
     * {@code 207 Multi-Status} (WebDAV - RFC 2518)
     * or
     * {@code 207 Partial Update OK} (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?)
     */
    public static final int SC_MULTI_STATUS = 207;

    // --- 3xx Redirection ---

    /** {@code 300 Mutliple Choices} (HTTP/1.1 - RFC 2616) */
    public static final int SC_MULTIPLE_CHOICES = 300;
    /** {@code 301 Moved Permanently} (HTTP/1.0 - RFC 1945) */
    public static final int SC_MOVED_PERMANENTLY = 301;
    /** {@code 302 Moved Temporarily} (Sometimes {@code Found}) (HTTP/1.0 - RFC 1945) */
    public static final int SC_MOVED_TEMPORARILY = 302;
    /** {@code 303 See Other} (HTTP/1.1 - RFC 2616) */
    public static final int SC_SEE_OTHER = 303;
    /** {@code 304 Not Modified} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NOT_MODIFIED = 304;
    /** {@code 305 Use Proxy} (HTTP/1.1 - RFC 2616) */
    public static final int SC_USE_PROXY = 305;
    /** {@code 307 Temporary Redirect} (HTTP/1.1 - RFC 2616) */
    public static final int SC_TEMPORARY_REDIRECT = 307;

    // --- 4xx Client Error ---

    /** {@code 400 Bad Request} (HTTP/1.1 - RFC 2616) */
    public static final int SC_BAD_REQUEST = 400;
    /** {@code 401 Unauthorized} (HTTP/1.0 - RFC 1945) */
    public static final int SC_UNAUTHORIZED = 401;
    /** {@code 402 Payment Required} (HTTP/1.1 - RFC 2616) */
    public static final int SC_PAYMENT_REQUIRED = 402;
    /** {@code 403 Forbidden} (HTTP/1.0 - RFC 1945) */
    public static final int SC_FORBIDDEN = 403;
    /** {@code 404 Not Found} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NOT_FOUND = 404;
    /** {@code 405 Method Not Allowed} (HTTP/1.1 - RFC 2616) */
    public static final int SC_METHOD_NOT_ALLOWED = 405;
    /** {@code 406 Not Acceptable} (HTTP/1.1 - RFC 2616) */
    public static final int SC_NOT_ACCEPTABLE = 406;
    /** {@code 407 Proxy Authentication Required} (HTTP/1.1 - RFC 2616)*/
    public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
    /** {@code 408 Request Timeout} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUEST_TIMEOUT = 408;
    /** {@code 409 Conflict} (HTTP/1.1 - RFC 2616) */
    public static final int SC_CONFLICT = 409;
    /** {@code 410 Gone} (HTTP/1.1 - RFC 2616) */
    public static final int SC_GONE = 410;
    /** {@code 411 Length Required} (HTTP/1.1 - RFC 2616) */
    public static final int SC_LENGTH_REQUIRED = 411;
    /** {@code 412 Precondition Failed} (HTTP/1.1 - RFC 2616) */
    public static final int SC_PRECONDITION_FAILED = 412;
    /** {@code 413 Request Entity Too Large} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUEST_TOO_LONG = 413;
    /** {@code 414 Request-URI Too Long} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUEST_URI_TOO_LONG = 414;
    /** {@code 415 Unsupported Media Type} (HTTP/1.1 - RFC 2616) */
    public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    /** {@code 416 Requested Range Not Satisfiable} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    /** {@code 417 Expectation Failed} (HTTP/1.1 - RFC 2616) */
    public static final int SC_EXPECTATION_FAILED = 417;

    /**
     * Static constant for a 418 error.
     * {@code 418 Unprocessable Entity} (WebDAV drafts?)
     * or {@code 418 Reauthentication Required} (HTTP/1.1 drafts?)
     */
    // not used
    // public static final int SC_UNPROCESSABLE_ENTITY = 418;

    /**
     * Static constant for a 419 error.
     * {@code 419 Insufficient Space on Resource}
     * (WebDAV - draft-ietf-webdav-protocol-05?)
     * or {@code 419 Proxy Reauthentication Required}
     * (HTTP/1.1 drafts?)
     */
    public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419;
    /**
     * Static constant for a 420 error.
     * {@code 420 Method Failure}
     * (WebDAV - draft-ietf-webdav-protocol-05?)
     */
    public static final int SC_METHOD_FAILURE = 420;
    /** {@code 422 Unprocessable Entity} (WebDAV - RFC 2518) */
    public static final int SC_UNPROCESSABLE_ENTITY = 422;
    /** {@code 423 Locked} (WebDAV - RFC 2518) */
    public static final int SC_LOCKED = 423;
    /** {@code 424 Failed Dependency} (WebDAV - RFC 2518) */
    public static final int SC_FAILED_DEPENDENCY = 424;

    // --- 5xx Server Error ---

    /** {@code 500 Server Error} (HTTP/1.0 - RFC 1945) */
    public static final int SC_INTERNAL_SERVER_ERROR = 500;
    /** {@code 501 Not Implemented} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NOT_IMPLEMENTED = 501;
    /** {@code 502 Bad Gateway} (HTTP/1.0 - RFC 1945) */
    public static final int SC_BAD_GATEWAY = 502;
    /** {@code 503 Service Unavailable} (HTTP/1.0 - RFC 1945) */
    public static final int SC_SERVICE_UNAVAILABLE = 503;
    /** {@code 504 Gateway Timeout} (HTTP/1.1 - RFC 2616) */
    public static final int SC_GATEWAY_TIMEOUT = 504;
    /** {@code 505 HTTP Version Not Supported} (HTTP/1.1 - RFC 2616) */
    public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

    /** {@code 507 Insufficient Storage} (WebDAV - RFC 2518) */
    public static final int SC_INSUFFICIENT_STORAGE = 507;
}

httpResult统一的请求结果

##设置回调
$!callback.setFileName("HttpResult.java")
$!callback.setSavePath($tool.append($tableInfo.savePath, "/http"))
##使用宏定义设置回调(保存位置与文件后缀)
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}http;



/**
 * HTTP结果封装
 *
 * @author $!author
 * @since $!time.currTime()
 */
public class HttpResult {
    private int code = 200;
    private String msg;
    private Object data;

    public static HttpResult error() {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
    }

    public static HttpResult error(String msg) {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    }

    public static HttpResult error(int code, String msg) {
        HttpResult r = new HttpResult();
        r.setCode(code);
        r.setMsg(msg);
        return r;
    }

    public static HttpResult ok(String msg) {
        HttpResult r = new HttpResult();
        r.setMsg(msg);
        return r;
    }

    public static HttpResult ok(Object data) {
        HttpResult r = new HttpResult();
        r.setData(data);
        return r;
    }

    public static HttpResult ok() {
        return new HttpResult();
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

}

配置好之后点击OK即可。

配置easy code 数据源

点击添加,选择data source ,并选择mysql。
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第11张图片
配置数据源信息
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第12张图片
配置完成之后可以看到如下信息。(由于我已经配置好,很简单,如果有问题可以百度参考其他文章,由于我太懒了,直接用现成的了)
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第13张图片
选择需要生成的表,比如我这里的user。选择easy code -> generate code。
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第14张图片
在弹窗中选择我们的module,并配置package路径。全选我们的template,同时将禁止提示勾选。单击OK即可。
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第15张图片
自动生成后的项目结构
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第16张图片

测试

在ChenApplication右键运行
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第17张图片
控制台输出:

[2020-03-24 00:05:29.486] boot -  INFO [background-preinit] --- Version: HV000001: Hibernate Validator 6.0.18.Final

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.5.RELEASE)

[2020-03-24 00:05:29.798] boot -  INFO [main] --- ChenApplication: Starting ChenApplication on root-PC with PID 9412 (D:\nanligong\mianshi\project\easy_code\easymapper\target\classes started by Administrator in D:\nanligong\mianshi\project\easy_code)
[2020-03-24 00:05:29.799] boot -  INFO [main] --- ChenApplication: No active profile set, falling back to default profiles: default
[2020-03-24 00:05:31.443] boot -  INFO [main] --- TomcatWebServer: Tomcat initialized with port(s): 8082 (http)
[2020-03-24 00:05:31.580] boot -  INFO [main] --- ContextLoader: Root WebApplicationContext: initialization completed in 1698 ms
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
[2020-03-24 00:05:31.752] boot -  INFO [main] --- DruidDataSourceAutoConfigure: Init DruidDataSource
[2020-03-24 00:05:31.878] boot -  INFO [main] --- DruidDataSource: {dataSource-1} inited
Using VFS adapter tk.mybatis.mapper.autoconfigure.SpringBootVFS
Checking to see if class com.njust.easymapper.entity.User matches criteria [is assignable to Object]
Scanned package: 'com.njust.easymapper.entity' for aliases
Parsed mapper file: 'file [D:\nanligong\mianshi\project\easy_code\easymapper\target\classes\mapper\UserMapper.xml]'
[2020-03-24 00:05:32.553] boot -  INFO [main] --- PropertySourcedRequestMappingHandlerMapping: Mapped URL path [/v2/api-docs] onto method [springfox.documentation.swagger2.web.Swagger2Controller#getDocumentation(String, HttpServletRequest)]
[2020-03-24 00:05:32.640] boot -  INFO [main] --- ThreadPoolTaskExecutor: Initializing ExecutorService 'applicationTaskExecutor'
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
[2020-03-24 00:05:32.832] boot -  INFO [main] --- DocumentationPluginsBootstrapper: Context refreshed
[2020-03-24 00:05:32.851] boot -  INFO [main] --- DocumentationPluginsBootstrapper: Found 1 custom documentation plugin(s)
[2020-03-24 00:05:32.886] boot -  INFO [main] --- ApiListingReferenceScanner: Scanning for api listing references
[2020-03-24 00:05:33.125] boot -  INFO [main] --- TomcatWebServer: Tomcat started on port(s): 8082 (http) with context path ''
[2020-03-24 00:05:33.129] boot -  INFO [main] --- ChenApplication: Started ChenApplication in 3.876 seconds (JVM running for 7.224)
[2020-03-24 00:06:05.258] boot -  INFO [http-nio-8082-exec-1] --- DispatcherServlet: Initializing Servlet 'dispatcherServlet'
[2020-03-24 00:06:05.267] boot -  INFO [http-nio-8082-exec-1] --- DispatcherServlet: Completed initialization in 8 ms

控制台显示程序运行正确。输入swagger网址,我们可以看到api接口页面。
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第18张图片
选择selectOne测试
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第19张图片
成功输出信息
EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程_第20张图片

GitHub源码地址

https://github.com/androidkaifa1/encapsulation

总结

暂时就写这么多吧!源码封装就不分析了,读者感兴趣的可以生成之后阅读。以后有时间在写一篇解释吧!没有写一行代码。项目直接可以运行的脚手架。最后祝读者身体健康,万事如意。

你可能感兴趣的:(EasyCode+通用Mapper+封装Spring Boot+Swagger脚手架详细教程)