使用 EasyCode生成springboot+mybatis基礎程序的實現示例

一、前言

此文將分享我個人使用的一個easycode生成方法,生成之後可以直接運行,這也就意味著,生成的代碼會更加規范化。規范化就意味著會有更多的約束。

二、正文

2.1 基礎前提

2.1.1springboot配置

引入所需jar包
pom.xml加入一下依賴

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

        <!--Swagger3-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>

application.yml配置

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://ip:3306/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username: xxx
    password: xxx

mybatis:
  type-aliases-package: xxx.entity
  mapper-locations: classpath:mapper/*.xml

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

#showSql
logging:
  level:
    top:
      yuechenc:
        yueduapi:
          mapper : debug

2.1.1 基礎工具類

以下是我個人封裝的pagehelper分頁工具類和統一的返回以及swagger配置

pagehelper工具類

在這裡插入圖片描述

如上圖所示,在啟動類所在目錄下新建目錄common.page/common.util
在page目錄新建類PageRequest.java

package xxx.common.page;

/**
 * @author Zhiwei Wang
 * @version $1.0
 * @description 分頁請求
 * @date 2022/1/19 9:25
 * @history
 */
public class PageRequest {
    /**
     * 當前頁碼
     */
    private int pageNum;
    /**
     * 每頁數量
     */
    private int pageSize;

    public PageRequest(int start, int limit) {
        pageNum=start;
        pageSize=limit;
    }

    public int getPageNum() {
        return pageNum;
    }
    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
}

在page目錄新建類PageResult.java

package xxx.common.page;

import java.util.List;

/**
 * @author Zhiwei Wang
 * @version $1.0
 * @name PageResult
 * @description 分頁返回結果
 * @date 2022/1/19 9:25
 * @history
 */
public class PageResult {
    /**
     * 當前頁碼
     */
    private int pageNum;
    /**
     * 每頁數量
     */
    private int pageSize;
    /**
     * 記錄總數
     */
    private long totalSize;
    /**
     * 頁碼總數
     */
    private int totalPages;
    /**
     * 數據模型
     */
    private List<?> content;

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public long getTotalSize() {
        return totalSize;
    }

    public void setTotalSize(long totalSize) {
        this.totalSize = totalSize;
    }

    public int getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }

    public List<?> getContent() {
        return content;
    }

    public void setContent(List<?> content) {
        this.content = content;
    }
}

在util目錄下新建工具類PageUtils.java

package xxx.common.util;

import com.github.pagehelper.PageInfo;
import xxx.common.page.PageRequest;
import xxx.common.page.PageResult;

/**
 * @author Zhiwei Wang
 * @version $
 * @name PageUtil
 * @description 
 * @date 2022/1/19 9:26
 * @history
 */
public class PageUtils {

    /**
     * 將分頁信息封裝到統一的接口
     * @param pageRequest
     * @param pageInfo
     * @return
     */
    public static PageResult getPageResult(PageRequest pageRequest, PageInfo<?> pageInfo) {
        PageResult pageResult = new PageResult();
        pageResult.setPageNum(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setTotalSize(pageInfo.getTotal());
        pageResult.setTotalPages(pageInfo.getPages());
        pageResult.setContent(pageInfo.getList());
        return pageResult;
    }
}

統一返回體
在common目錄下新建Status.java

package xxx.common;

/**
 * @author Zhiwei Wang
 * @version $
 * @name Status
 * @description 返回信息枚舉
 * @date 2022/1/18 21:01
 * @history
 */
public enum Status {

    FAIL("101", "失敗")
    ,GET_FAIL("111", "查詢失敗")
    ,ADD_FAIL("121", "添加失敗")
    ,DELETE_FAIL("131", "刪除失敗")
    ,UPDATE_FAIL("141", "修改失敗")
    ,SUCCESS("100", "成功")
    ,GET_SUCCESS("110", "查詢成功")
    ,ADD_SUCCESS("120", "添加成功")
    ,DELETE_SUCCESS("130", "刪除成功")
    ,UPDATE_SUCCESS("140", "修改成功")
    ,ERROR("201", "錯誤")
    ,USER_NOFOUND("211", "用戶不存在")
    ,ERROR_ACCOUNT("212", "賬號或密碼錯誤")
    ,USER_EXIST("213", "用戶已存在")
    ,USER_LOCK("214", "賬號被鎖定,請聯系管理員")
    ,IP_LOCK("215", "IP 被鎖定,請聯系管理員")
    ,PARAM_ERROR("303", "參數錯誤")
    ,Token_Expired("1044", "token Invalid expired");

    public String status; // 狀態碼
    public String msg; // 提示語

    Status(String status, String msg) {
        this.status = status;
        this.msg = msg;
    }

}

在common目錄下新建ReturnData.java

package xxx.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * @author Zhiwei Wang
 * @version $
 * @name ReturnData
 * @description 響應數據結構封裝
 * @date 2022/1/18 20:59
 * @history
 */
public class ReturnData<T> {
    private String status; // 狀態碼

    private String msg; // 提示語

    private T data;  // 數據集合

    public static <T> ReturnData<T> SUCCESS(T data) {
        return new ReturnData<T>(Status.SUCCESS.status, Status.SUCCESS.msg, data);
    }

    public static <T> ReturnData<T> SUCCESS(String msg) {
        return new ReturnData<T>(Status.SUCCESS.status, msg);
    }

    public static <T> ReturnData<T> SUCCESS() {
        return new ReturnData<T>(Status.SUCCESS.status, Status.SUCCESS.msg);
    }

    public static <T> ReturnData<T> GET_SUCCESS(T data) {
        return new ReturnData<T>(Status.GET_SUCCESS.status, Status.GET_SUCCESS.msg, data);
    }

    public static <T> ReturnData<T> GET_SUCCESS(String msg) {
        return new ReturnData<T>(Status.GET_SUCCESS.status, msg);
    }

    public static <T> ReturnData<T> GET_SUCCESS() {
        return new ReturnData<T>(Status.GET_SUCCESS.status, Status.GET_SUCCESS.msg);
    }


    public static <T> ReturnData<T> ADD_SUCCESS() {
        return new ReturnData<T>(Status.ADD_SUCCESS.status, Status.ADD_SUCCESS.msg);
    }

    public static <T> ReturnData<T> ADD_SUCCESS(T data) {
        return new ReturnData<T>(Status.ADD_SUCCESS.status, Status.ADD_SUCCESS.msg,data);
    }

    public static <T> ReturnData<T> DELETE_SUCCESS() {
        return new ReturnData<T>(Status.DELETE_SUCCESS.status, Status.DELETE_SUCCESS.msg);
    }

    public static <T> ReturnData<T> UPDATE_SUCCESS() {
        return new ReturnData<T>(Status.UPDATE_SUCCESS.status, Status.UPDATE_SUCCESS.msg);
    }

    public static <T> ReturnData<T> UPDATE_SUCCESS(T data) {
        return new ReturnData<T>(Status.UPDATE_SUCCESS.status, Status.UPDATE_SUCCESS.msg,data);
    }

    public static <T> ReturnData<T> FAIL(String msg) {
        return new ReturnData<T>(Status.FAIL.status, msg);
    }

    public static <T> ReturnData<T> FAIL() {
        return new ReturnData<T>(Status.FAIL.status, Status.FAIL.msg);
    }

    public static <T> ReturnData<T> GET_FAIL(String msg) {
        return new ReturnData<T>(Status.GET_FAIL.status, msg);
    }

    public static <T> ReturnData<T> GET_FAIL() {
        return new ReturnData<T>(Status.GET_FAIL.status, Status.FAIL.msg);
    }


    public static <T> ReturnData<T> ADD_FAIL() {
        return new ReturnData<T>(Status.ADD_FAIL.status, Status.ADD_FAIL.msg);
    }

    public static <T> ReturnData<T> DELETE_FAIL() {
        return new ReturnData<T>(Status.DELETE_FAIL.status, Status.DELETE_FAIL.msg);
    }

    public static <T> ReturnData<T> UPDATE_FAIL() {
        return new ReturnData<T>(Status.UPDATE_FAIL.status, Status.UPDATE_FAIL.msg);
    }

    public static <T> ReturnData<T> ERROR(String msg) {
        return new ReturnData<T>(Status.ERROR.status, msg);
    }

    public static <T> ReturnData<T> ERROR() {
        return new ReturnData<T>(Status.ERROR.status, Status.ERROR.msg);
    }


    public ReturnData(String status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public ReturnData(String status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

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

    public T getData() {
        return data;
    }

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

    /**
     * 如果字段為null,該字段不顯示
     */
    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    /**
     * 返回全部字段,包括null
     *
     * @return
     */
    public String toAllString() {
        return JSON.toJSONString(this, SerializerFeature.WriteMapNullValue);
    }

}

swagger3配置
在common目錄下新建Swagger3Config.java

package xxx.common;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * @author Zhiwei Wang
 * @version $
 * @name Swagger3Config
 * @description
 * @date 2022/1/18 21:40
 * @history
 */
@Configuration
public class Swagger3Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("xxx.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3接口文檔")
                .description("測試API")
                .contact(new Contact("測試API", "http://localhost:8080/swagger-ui/index.html", "[email protected]"))
                .version("1.0")
                .build();
    }
}

2.2 模板設置

2.2.1安裝idea插件:EasyCode

在這裡插入圖片描述

如圖所示,打開idea的設置界面,選擇插件,搜索EasyCode,點擊安裝即可

2.2.2 設置模板

在這裡插入圖片描述

如圖:依次打開idea設置-> 其他設置->EasyCode-MyBatisCodeHelper->Template Setting
右邊的就是生成代碼的模板,一次將下列模板粘貼到裡面即可:

entity

##引入宏定義
$!define

##使用宏定義設置回調(保存位置與文件後綴)
#save("/entity", ".java")

##使用宏定義設置包後綴
#setPackageSuffix("entity")

##使用全局變量實現默認包導入
$!autoImport
import java.io.Serializable;

##使用宏定義實現類註釋信息
#tableComment("實體類")
public class $!{tableInfo.name} implements Serializable {
    private static final long serialVersionUID = $!tool.serial();
#foreach($column in $tableInfo.fullColumn)
    #if(${column.comment})/**
    * ${column.comment}
    */#end

    private $!{tool.getClsNameByFullName($column.type)} $!{column.name};
#end

#foreach($column in $tableInfo.fullColumn)
    ##使用宏定義實現get,set方法
    #getSetMethod($column)
#end

    @Override
    public String toString(){
        return "$tableInfo.name {" +
        #foreach($column in $tableInfo.fullColumn)
    "$column.name : " + $column.name + ", " +
        #end        
'}';
    }
}

dao

##定義初始變量
#set($tableName = $tool.append($tableInfo.name, "Dao"))
##設置回調
$!callback.setFileName($tool.append($tableName, ".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath, "/dao"))

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

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

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

/**
 * $!{tableInfo.comment}($!{tableInfo.name})表數據庫訪問層
 *
 * @author $!author
 * @since $!time.currTime()
 */
public interface $!{tableName} {

    /**
     * 通過ID查詢單條數據
     *
     * @param $!pk.name 主鍵
     * @return 實例對象
     */
    $!{tableInfo.name} selectById($!pk.shortType $!pk.name);
	
    /**
     * 分頁查詢
     *
     * @param start 查詢起始位置
     * @param limit 查詢條數
     * @return 對象列表
     */
    List<$!{tableInfo.name}> selectPage(@Param("start") int start, @Param("limit") int limit);

    /**
     * 查詢全部
     *
     * @return 對象列表
     */
    List<$!{tableInfo.name}> selectAll();
    
    /**
     * 通過實體作為篩選條件查詢
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 實例對象
     * @return 對象列表
     */
    List<$!{tableInfo.name}> selectList($!{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})s 實例對象的集合
     * @return 影響行數
     */
	int batchInsert(List<$!{tableInfo.name}> $!tool.firstLowerCase($!{tableInfo.name})s);
	
    /**
     * 修改數據
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 實例對象
     * @return 影響行數
     */
    int update($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));

    /**
     * 通過主鍵刪除數據
     *
     * @param $!pk.name 主鍵
     * @return 影響行數
     */
    int deleteById($!pk.shortType $!pk.name);

    /**
     * 查詢總數據數
     *
     * @return 數據總數
     */
    int count();
}

service

##定義初始變量
#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;
import java.util.Map;
import $!{tableInfo.savePackageName}.common.page.PageResult;

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

    /**
     * 通過ID查詢單條數據
     *
     * @param $!pk.name 主鍵
     * @return 實例對象
     */
    $!{tableInfo.name} selectById($!pk.shortType $!pk.name);

    /**
     * 分頁查詢
     *
     * @param start 查詢起始位置
     * @param limit 查詢條數
     * @return 對象列表
     */
    PageResult selectPage(int start, int limit);

    /**                                                                        
     * 查詢全部
     *
     * @return 對象列表
     */
    List<$!{tableInfo.name}> selectAll();
    
    /**
     * 通過實體作為篩選條件查詢
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 實例對象
     * @return 對象列表
     */
    List<$!{tableInfo.name}> selectList($!{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})s 實例對象的集合
     * @return 影響行數
     */
	int batchInsert(List<$!{tableInfo.name}> $!tool.firstLowerCase($!{tableInfo.name})s);
	
    /**
     * 修改數據
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 實例對象
     * @return 修改
     */
    $!{tableInfo.name} update($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name}));

    /**
     * 通過主鍵刪除數據
     *
     * @param $!pk.name 主鍵
     * @return 影響行數
     */
    int deleteById($!pk.shortType $!pk.name);
    
    /**
     * 查詢總數據數
     *
     * @return 數據總數
     */
    int count();
}

serviceimpl

##定義初始變量
#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}.entity.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.dao.$!{tableInfo.name}Dao;
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.stereotype.Service;
import $!{tableInfo.savePackageName}.common.page.PageResult;
import $!{tableInfo.savePackageName}.common.page.PageRequest;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import $!{tableInfo.savePackageName}.common.util.PageUtils;

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

/**
 * $!{tableInfo.comment}($!{tableInfo.name}表)服務實現類
 *
 * @author $!author
 * @since $!time.currTime()
 */
@Service("$!tool.firstLowerCase($!{tableInfo.name})Service")
public class $!{tableName} implements $!{tableInfo.name}Service {
    @Resource
    private $!{tableInfo.name}Dao $!tool.firstLowerCase($!{tableInfo.name})Dao;

    /**
     * 通過ID查詢單條數據
     *
     * @param $!pk.name 主鍵
     * @return 實例對象
     */
    @Override
    public $!{tableInfo.name} selectById($!pk.shortType $!pk.name) {
        return this.$!{tool.firstLowerCase($!{tableInfo.name})}Dao.selectById($!pk.name);
    }

    /**
     * 分頁查詢
     *
     * @param start 查詢起始位置
     * @param limit 查詢條數
     * @return 對象列表
     */
    @Override
    public PageResult selectPage(int start, int limit) {
        PageRequest pageRequest=new PageRequest(start,limit);
        return PageUtils.getPageResult(pageRequest, getPageInfo(pageRequest));
    }

    /**
     * 調用分頁插件完成分頁
     * @param pageRequest
     * @return
     */
    private PageInfo<$!{tableInfo.name}> getPageInfo(PageRequest pageRequest) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<$!{tableInfo.name}> $!{tool.firstLowerCase($!{tableInfo.name})}s = this.$!{tool.firstLowerCase($!{tableInfo.name})}Dao.selectAll();
        return new PageInfo<>($!{tool.firstLowerCase($!{tableInfo.name})}s);
    }

    /**
     * 查詢所有
     *
     * @return 實例對象的集合
     */
    @Override
    public List<$!{tableInfo.name}> selectAll() {
        return this.$!{tool.firstLowerCase($!{tableInfo.name})}Dao.selectAll();
    }
    
    /**
     * 根據條件查詢
     *
     * @return 實例對象的集合
     */
    @Override
    public List<$!{tableInfo.name}> selectList($!{tableInfo.name} $!{tool.firstLowerCase($!{tableInfo.name})}) {
        return this.$!{tool.firstLowerCase($!{tableInfo.name})}Dao.selectList($!{tool.firstLowerCase($!{tableInfo.name})});
    }
    
    /**
     * 新增數據
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 實例對象
     * @return 實例對象
     */
    @Override
    public int insert($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name})) {
        return this.$!{tool.firstLowerCase($!{tableInfo.name})}Dao.insert($!tool.firstLowerCase($!{tableInfo.name}));
    }

    /**
     * 批量新增
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name})s 實例對象的集合
     * @return 生效的條數
     */
    @Override
    public int batchInsert(List<$!{tableInfo.name}> $!tool.firstLowerCase($!{tableInfo.name})s) {
        return this.$!{tool.firstLowerCase($!{tableInfo.name})}Dao.batchInsert($!tool.firstLowerCase($!{tableInfo.name})s);
    }

    /**
     * 修改數據
     *
     * @param $!tool.firstLowerCase($!{tableInfo.name}) 實例對象
     * @return 實例對象
     */
    @Override
    public $!{tableInfo.name} update($!{tableInfo.name} $!tool.firstLowerCase($!{tableInfo.name})) {
        this.$!{tool.firstLowerCase($!{tableInfo.name})}Dao.update($!tool.firstLowerCase($!{tableInfo.name}));
        return this.selectById($!{tool.firstLowerCase($!{tableInfo.name})}.get$!tool.firstUpperCase($pk.name)());
    }

    /**
     * 通過主鍵刪除數據
     *
     * @param $!pk.name 主鍵
     * @return 是否成功
     */
    @Override
    public int deleteById($!pk.shortType $!pk.name) {
        return this.$!{tool.firstLowerCase($!{tableInfo.name})}Dao.deleteById($!pk.name);
    }
    
    /**
     * 查詢總數據數
     *
     * @return 數據總數
     */
    @Override
    public int count(){
        return this.$!{tool.firstLowerCase($!{tableInfo.name})}Dao.count();
    }
}

controller

##定義初始變量
#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 org.springframework.web.bind.annotation.*;
import $!{tableInfo.savePackageName}.common.ReturnData;
import $!{tableInfo.savePackageName}.common.page.PageResult;
import java.util.List;

import javax.annotation.Resource;

/**
 * $!{tableInfo.comment}($!{tableInfo.name})控制層
 *
 * @author $!author
 * @since $!time.currTime()
 */
@RestController
@RequestMapping("/$!tool.firstLowerCase($tableInfo.name)")
public class $!{tableName} {
    /**
     * 服務對象
     */
    @Resource
    private $!{tableInfo.name}Service $!tool.firstLowerCase($tableInfo.name)Service;

    /**
     * 通過主鍵查詢單條數據
     *
     * @param $!tool.firstLowerCase($tableInfo.name) 參數對象
     * @return 單條數據
     */
    @RequestMapping(value = "get", method = RequestMethod.GET)
    public ReturnData<$tableInfo.name> selectOne($tableInfo.name $!tool.firstLowerCase($tableInfo.name)) {
        $tableInfo.name result = $!{tool.firstLowerCase($tableInfo.name)}Service.selectById($!{tool.firstLowerCase($tableInfo.name)}.getId());
        if(result != null){
            return ReturnData.GET_SUCCESS(result);
        }
        return ReturnData.GET_FAIL();
    }
    
    /**
     * 新增一條數據
     *
     * @param $!tool.firstLowerCase($tableInfo.name) 實體類
     * @return Response對象
     */
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public ReturnData<$tableInfo.name> insert(@RequestBody $tableInfo.name $!tool.firstLowerCase($tableInfo.name)) {
        int result = $!{tool.firstLowerCase($tableInfo.name)}Service.insert($!tool.firstLowerCase($tableInfo.name));
        if (result > 0) {
            return ReturnData.ADD_SUCCESS();
        }
        return ReturnData.ADD_FAIL();
    }

    /**
     * 修改一條數據
     *
     * @param $!tool.firstLowerCase($tableInfo.name) 實體類
     * @return Response對象
     */
    @RequestMapping(value = "update", method = RequestMethod.PUT)
    public ReturnData<$tableInfo.name> update(@RequestBody $tableInfo.name $!tool.firstLowerCase($tableInfo.name)) {
        $tableInfo.name result = $!{tool.firstLowerCase($tableInfo.name)}Service.update($!tool.firstLowerCase($tableInfo.name));
        if (result != null) {
            return ReturnData.UPDATE_SUCCESS(result);
        }
        return ReturnData.UPDATE_FAIL();
    }

    /**
     * 刪除一條數據
     *
     * @param $!tool.firstLowerCase($tableInfo.name) 參數對象
     * @return Response對象
     */
    @RequestMapping(value = "delete", method = RequestMethod.DELETE)
    public ReturnData<$tableInfo.name> delete($tableInfo.name $!tool.firstLowerCase($tableInfo.name)) {
        int result = $!{tool.firstLowerCase($tableInfo.name)}Service.deleteById($!{tool.firstLowerCase($tableInfo.name)}.getId());
        if (result > 0) {
            return ReturnData.DELETE_SUCCESS();
        }
        return ReturnData.DELETE_FAIL();
    }

    /**
     * 查詢全部
     *
     * @return Response對象
     */
    @RequestMapping(value = "selectAll", method = RequestMethod.GET)
    public ReturnData<List<$tableInfo.name>> selectAll() {
        List<$tableInfo.name> $!tool.firstLowerCase($tableInfo.name)s = $!{tool.firstLowerCase($tableInfo.name)}Service.selectAll();
        if ($!tool.firstLowerCase($tableInfo.name)s != null) {
            return ReturnData.GET_SUCCESS($!tool.firstLowerCase($tableInfo.name)s);
        }
        return ReturnData.GET_FAIL();
    }

    /**
     * 分頁查詢
     *
     * @param start 偏移
     * @param limit 條數
     * @return Response對象
     */
    @RequestMapping(value = "selectPage", method = RequestMethod.GET)
    public ReturnData<PageResult> selectPage(Integer start, Integer limit) {
        PageResult pageResult = $!{tool.firstLowerCase($tableInfo.name)}Service.selectPage(start, limit);
        if (pageResult != null) {
            return ReturnData.GET_SUCCESS(pageResult);
        }
        return ReturnData.GET_FAIL();
    }
    
}

mapper.xml

##引入mybatis支持
$!mybatisSupport

##設置保存名稱與保存位置
$!callback.setFileName($tool.append($!{tableInfo.name}, "Dao.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}.dao.$!{tableInfo.name}Dao">
    <!-- 結果集 -->
    <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>
    
    <!-- 基本字段 -->
    <sql id="Base_Column_List">
        #allSqlColumn()
    </sql>
    
    <!-- 查詢單個 -->
    <select id="selectById" resultMap="$!{tableInfo.name}Map">
        select
          <include refid="Base_Column_List" />
        from $!tableInfo.obj.name
        where $!pk.obj.name = #{$!pk.name}
    </select>

    <!-- 分頁查詢 -->
    <select id="selectPage" resultMap="$!{tableInfo.name}Map">
        select
        <include refid="Base_Column_List" />
        from $!tableInfo.obj.name
        limit #{start},#{limit}
    </select>

    <!-- 查詢全部 -->
    <select id="selectAll" resultMap="$!{tableInfo.name}Map">
        select
        <include refid="Base_Column_List" />
        from $!tableInfo.obj.name
    </select>

    <!--通過實體作為篩選條件查詢-->
    <select id="selectList" resultMap="$!{tableInfo.name}Map">
        select
        <include refid="Base_Column_List" />
        from $!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.name}(#foreach($column in $tableInfo.fullColumn)$!column.obj.name#if($velocityHasNext), #end#end)
        values ( #foreach($column in $tableInfo.fullColumn)#{$!{column.name}}#if($velocityHasNext), #end#end)
    </insert>
    
    <!-- 批量新增 -->
    <insert id="batchInsert">
        insert into $!{tableInfo.obj.name}(#foreach($column in $tableInfo.fullColumn)$!column.obj.name#if($velocityHasNext), #end#end)
        values 
        <foreach collection="$!tool.firstLowerCase($!{tableInfo.name})s" item="item" index="index" separator=",">
        (
            #foreach($column in $tableInfo.fullColumn)
            #{item.$!{column.name}}#if($velocityHasNext), #end
#end
         )
         </foreach>
    </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.name} where $!pk.obj.name = #{$!pk.name}
    </delete>
    
    <!-- 總數 -->
    <select id="count" resultType="int">
        select count(*) from $!{tableInfo.obj.name}
    </select>
</mapper>

2.3 生成方法

首先使用idea連接數據庫,此處省略,如果有不知道怎麼連接的,請參考:mysql連接idea詳細教程 

在這裡插入圖片描述

在這裡插入圖片描述

如圖選擇需要生成代碼的表->右鍵->EasyCodeMybatisCodeHelper->Generate_Code,彈出如下窗口

在這裡插入圖片描述

Module:選擇要生成到那個模塊
Package:填寫自己的包名
Path:工程路徑

選擇要生成的類,點擊ok即可看到工程裡已經生成瞭相應的類

在這裡插入圖片描述

註意:使用mybatis需要在啟動類中加入註釋 

//掃描dao的路徑配置
@MapperScan(".dao")

到此這篇關於使用 EasyCode生成springboot+mybatis基礎程序的實現示例的文章就介紹到這瞭,更多相關EasyCode生成springboot+mybatis基礎程序內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: