EasyCode+通用Mapper+封裝Spring Boot+Swagger腳手架詳細教程

新建工程

新建一個Module
在這裏插入圖片描述
選擇maven工程,並選擇jdk版本爲1.8,單擊next,直接進入下一步

在這裏插入圖片描述
這裏命名隨便寫,但是爲了減少出錯,第一次可以參考我的寫法,當然讀者也可以自由發揮。
在這裏插入圖片描述
命名好之後,單擊next。
在這裏插入圖片描述
單擊finish完成工程的創建,新建好的文件結構如下圖所示:
在這裏插入圖片描述

修改pom文件,添加需要的pom文件。廢話不多說,直接上源碼。
pom.xml

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <groupId>com.njust.easymapper</groupId>
    <artifactId>easymapper</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <dependencies>
        <!--引入SpringBoot起步依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--alibaba連接池 druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!--引入fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <!--引入數據庫連接驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <!--mybatis-start-->
        <!--引入mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--引入 mybatis-generator-core 才能使用逆向工程-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
            <scope>compile</scope>
            <optional>true</optional>
        </dependency>
        <!--mapper 引入可以使用通用mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.2.4</version>
        </dependency>
        <!--pagehelper 引入分頁插件依賴的jar包-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!--日誌-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j</artifactId>
            <version>1.3.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

    </dependencies>
    <!--2.引入插件-->
    <build>
        <plugins>
            <!--maven插件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!--引入分頁插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.29</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>4.0.0</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>


</project>

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

新建項目包
在這裏插入圖片描述
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
在這裏插入圖片描述

選擇File | Settings | Other Settings | Easy Code | Template Setting。
在這裏插入圖片描述
點擊添加按鈕,並命名爲njust(名稱可以隨便取),如下圖所示。
在這裏插入圖片描述

按照下圖所示新建一個個配置文件。
在這裏插入圖片描述

配置文件源代碼

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

<?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="$!{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)
            <if test="$!column.name != null#if($column.type.equals("java.lang.String")) and $!column.name != ''#end">
                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)
            <if test="$!column.name != null#if($column.type.equals("java.lang.String")) and $!column.name != ''#end">
                $!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。
在這裏插入圖片描述
配置數據源信息
在這裏插入圖片描述
配置完成之後可以看到如下信息。(由於我已經配置好,很簡單,如果有問題可以百度參考其他文章,由於我太懶了,直接用現成的了)
在這裏插入圖片描述
選擇需要生成的表,比如我這裏的user。選擇easy code -> generate code。
在這裏插入圖片描述
在彈窗中選擇我們的module,並配置package路徑。全選我們的template,同時將禁止提示勾選。單擊OK即可。
在這裏插入圖片描述
自動生成後的項目結構
在這裏插入圖片描述

測試

在ChenApplication右鍵運行
在這裏插入圖片描述
控制檯輸出:

[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接口頁面。
在這裏插入圖片描述
選擇selectOne測試
在這裏插入圖片描述
成功輸出信息
在這裏插入圖片描述

GitHub源碼地址

https://github.com/androidkaifa1/encapsulation

總結

暫時就寫這麼多吧!源碼封裝就不分析了,讀者感興趣的可以生成之後閱讀。以後有時間在寫一篇解釋吧!沒有寫一行代碼。項目直接可以運行的腳手架。最後祝讀者身體健康,萬事如意。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章