自定义Mybatis-generate(二)

31 篇文章 0 订阅
7 篇文章 0 订阅

需求描述:

        1,SpringBoot项目

        2,需要自动生成 controller层、service层、mapper接口、mapper.xml、实体类、自定义扩展类等

        3,连接的数据库是 gauss db

        4,mybatis-generate 本身的模板及模板参数固定,无法扩展到更多自定义类,需要更改源码实现

        5,自动生成单元测试类等操作

controller.ftl

package ${package.Controller};

import com.taia.yms.aop.UserDataPermission;
import com.taia.yms.auditlog.ModifyName;
import com.taia.yms.auditlog.aop.ModifyLog;
import com.taia.yms.entity.JsonResult;
import com.taia.yms.entity.reqbody.*;
import com.taia.yms.fileutils3.common.FileUtilsPack;
import com.taia.yms.fileutils3.entity.ProcessFileResult;
import com.taia.yms.service.${table.serviceName};
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;

/**
 * <p>
 * ${table.comment!} 前端控制器
 * </p>
 * @author ${author}
 * @since ${date}
 */
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("/${pathVersion}/${processName}/")
@Api(tags = "${apiTags}")
public class ${table.controllerName} {
    @Autowired
    ${table.serviceName} service;

    @PostMapping("save")
    @ApiOperation("新增或编辑保存")
    @ModifyLog(pageName = "${apiTags}", tableName = "${table.name}", voClass = ${reqBodyEntity}.class)
    public JsonResult saveOrUpdate(@Validated @RequestBody ${reqBodyEntity} reqBody) {
        return service.saveOrUpdate(reqBody);
    }

    @PostMapping("getList")
    @ApiOperation("获取分页数据")
    public JsonResult getList(@Validated @RequestBody ${pageReqBodyEntity} pageReqBody){
        return service.getList(pageReqBody);
    }

    @GetMapping("delete")
    @ApiOperation("删除(将status改为9)")
    @ModifyLog(pageName = "${apiTags}",type = ModifyName.DELETE)
    public JsonResult delete(@Validated @NotEmpty(message = "id为空") @RequestParam String ids){
        return service.delete(ids);
    }

    @PostMapping("export")
    @ApiOperation("导出文件")
    @UserDataPermission
    public void exportFile(HttpServletResponse response, @RequestBody ${pageReqBodyEntity} pageReqBody){
        ProcessFileResult processFileResult = service.exportFile(pageReqBody);
        FileUtilsPack.getExportFileResult(response,processFileResult);
    }
    @PostMapping("import")
    @ApiOperation("导入文件")
    public JsonResult importFile(@RequestParam MultipartFile file) {
        return service.importFile(file);
    }

}

service.ftl 接口

package ${package.Service};

import com.taia.yms.entity.JsonResult;
import org.springframework.web.multipart.MultipartFile;
import com.taia.yms.entity.reqbody.${reqBodyEntity};
import com.taia.yms.entity.reqbody.${pageReqBodyEntity};
import com.taia.yms.fileutils3.entity.ProcessFileResult;
/**
 * <p>
 * ${table.comment!} 服务类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} {
    /**
    * 新增或编辑保存
    */
    JsonResult saveOrUpdate(${reqBodyEntity} reqBody);

    /**
    * 批量删除数据
    */
    JsonResult delete(String ids);

    /**
    * 导出文件
    */
    ProcessFileResult exportFile(${pageReqBodyEntity} pageReqBody);

    /**
    * 导入文件
    */
    JsonResult importFile(MultipartFile file);

    /**
    * 获取分页数据
    */
    JsonResult getList(${pageReqBodyEntity} pageReqBody);
}
</#if>

serviceImpl.ftl

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.taia.yms.auditlog.ModifyName;
import com.taia.yms.auditlog.aop.ModifyLog;
import com.taia.yms.config.ThreadLocalConf;
import com.taia.yms.entity.*;
import com.taia.yms.fileutils3.common.FileUtilDefaultContext;
import com.taia.yms.fileutils3.common.FileUtilsPack;
import com.taia.yms.fileutils3.entity.ProcessFileResult;
import com.taia.yms.fileutils3.service.${fileEntity};
import com.taia.yms.service.myimpl.CommonImpl;
import com.taia.yms.service.myimpl.ServiceUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.taia.yms.entity.reqbody.*;
/**
 * <p>
 * ${table.comment!} 服务实现类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Service
@Slf4j
public class ${table.serviceImplName} implements ${table.serviceName} {
    @Autowired
    ${table.mapperName} mapper;

    @Override
    public JsonResult saveOrUpdate(${reqBodyEntity} reqBody) {
        reqBody.setLastUpdatedBy(ThreadLocalConf.getUserId()).setLastUpdatedByName(ThreadLocalConf.getUserName());
        if(Objects.isNull(reqBody.getId())){
            reqBody.setCreatedBy(ThreadLocalConf.getUserId()).setCreatedByName(ThreadLocalConf.getUserName());
        }
        // 重复提示信息
        String promptMsg = "${primaryKeyStr}";
        promptMsg = String.format(promptMsg, ${getPrimaryKeyStr});
        // 业务操作
        CommonImpl commonImpl = new CommonImpl(${table.mapperName}.class, promptMsg);
        return commonImpl.saveOrUpdateData(reqBody);
    }

    @Override
    public JsonResult delete(String ids) {
        DeleteIdList deleteInfo = ServiceUtils.getDeleteInfo(ids);
        mapper.batchDelDataById(deleteInfo);
        return JsonResult.ok();
    }

    @Override
    public ProcessFileResult exportFile(${pageReqBodyEntity} pageReqBody) {
        Supplier<List<${table.entityName}>> configSupplier = () -> mapper.selectConfigList(pageReqBody);
        FileUtilDefaultContext fc = ServiceUtils.exportFile(new ${fileEntity}(),pageReqBody,configSupplier);
        return fc.getProcessFileResult();
    }

    @Override
    public JsonResult importFile(MultipartFile file) {
        FileUtilDefaultContext fc = FileUtilsPack.getFileUtilContext(new ${fileEntity}());
        List<${reqBodyEntity}> detailTabList = fc.importFileToBean(file, ${reqBodyEntity}.class);
        ${table.serviceImplName} serviceImpl = (${table.serviceImplName}) AopContext.currentProxy();
        serviceImpl.insertDataList(detailTabList);
        return FileUtilsPack.getImportFileResult(fc.getProcessFileResult());
    }

    @Transactional
    @ModifyLog(pageName = "${apiTags}", type = ModifyName.IMPORT)
    public void insertDataList(List<${reqBodyEntity}> dataList) {
        // 分批插入
        if (!CollectionUtils.isEmpty(dataList)) {
           List<List<${reqBodyEntity}>> importBatches = ListUtils.partition(dataList, 500);
           for (List<${reqBodyEntity}> importBatch : importBatches) {
               mapper.batchMergeByIndex(importBatch);
           }
         }
     }

    /**
    * 获取分页数据
    */
    @Override
    public JsonResult getList(${pageReqBodyEntity} pageReqBody) {
        Page<${table.entityName}> page = PageMethod.startPage(pageReqBody.getPageNum(), pageReqBody.getPageSize());
        List<${table.entityName}> configVoList = mapper.selectConfigList(pageReqBody);
        return JsonResult.ok(new PageInfoVo<>(page.getTotal(), configVoList));
    }
}

mapper接口

package ${package.Mapper};

import com.taia.yms.entity.reqbody.*;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import ${package.Entity}.${table.entityName};
import com.taia.yms.entity.DeleteIdList;
/**
* <p>
    * ${table.comment!} Mapper 接口
    * </p>
*
* @author ${author}
* @since ${date}
*/
<#if kotlin>
    interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
    @Mapper
    public interface ${table.mapperName}{
        /**
        * 根据索引查询id(判断是否数据重复)
        */
        List<Long> selectIdsByIndex(${reqBodyEntity} reqBody);
        /**
        * 单条更新(根据id条件)
        */
        int updById(${table.entityName} saveTab);
        /**
        * 单条插入/更新(根据索引条件merge into)
        */
        int mergeByIndex(${table.entityName} saveTab);
        /**
        * 查询已配置数据(支持字段模糊查询)
        */
        List<${table.entityName}> selectConfigList(${pageReqBodyEntity} pageReqBody);
        /**
        * 批量删除(根据id条件)
        */
        int batchDelDataById(DeleteIdList deleteInfo);

        /**
        * 批量插入/更新(根据索引条件merge into)
        */
        int batchMergeByIndex(List<${reqBodyEntity}> batchList);
    }
</#if>

mapper.xml 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${package.Mapper}.${table.mapperName}">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
        <#list table.fields as field>
            <#if field.keyFlag><#--生成主键排在第一位-->
                <id column="${field.name}" property="${field.propertyName}" />
            </#if>
        </#list>
        <#list table.commonFields as field><#--生成公共字段 -->
            <result column="${field.name}" property="${field.propertyName}" />
        </#list>
        <#list table.fields as field>
            <#if !field.keyFlag><#--生成普通字段 -->
                <result column="${field.name}" property="${field.propertyName}" />
            </#if>
        </#list>
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        <#list table.commonFields as field>
            ${field.columnName},
        </#list>
        ${table.fieldNames}
    </sql>

    <!--单条插入/更新(根据索引条件merge into)-->
    <insert id="mergeByIndex">
        MERGE INTO ${table.name} t
        USING
        <trim prefix="(" suffix=")">
            SELECT
            <#-- 字段属性 -->
            <#assign text = '#\{'>
            <#-- ----------  BEGIN 字段循环遍历  ---------->
            <#list table.fields as field>
                <#-- 展示非主键字段 -->
                <#if !field.keyFlag>
                    <#assign propertyNameColumn = "${text} ${field.propertyName} }">
                    <#--   重新赋值  -->
                    <#if field.propertyName=='status'>
                        <#assign propertyNameColumn = 1>
                    <#elseif field.propertyName=='lastUpdatedTime'>
                        <#assign propertyNameColumn = 'CURRENT_TIMESTAMP'>
                    <#elseif field.propertyName=='createdTime'>
                        <#assign propertyNameColumn = 'CURRENT_TIMESTAMP'>
                    </#if>
                    ${propertyNameColumn} as ${field.propertyName} <#if field_index!=(table.fields?size - 1)>,</#if>
                </#if>
            </#list>
            <#------------  END 字段循环遍历  ---------->
            from sys_dummy
        </trim> AS o
        ON
        <trim prefix="(" suffix=")">
            <#list primaryKeys as field>
                <#list table.fields as field1>
                    <#if field == field1.name>
                        <#if field_index!=0>
                            AND
                        </#if>
                        t.${field1.name} = o.${field1.propertyName}
                    </#if>
                </#list>
            </#list>
            <#list table.fields as field1>
                <#if field1.propertyName=='status'>
                    AND
                    t.status != '9'
                </#if>
            </#list>
        </trim>
        WHEN MATCHED THEN
        UPDATE SET
        <#list table.fields as field>
        <#-- 展示非主键字段 -->
            <#if !field.keyFlag && field.propertyName != 'createdBy' && field.propertyName != 'createByName' && field.propertyName != 'createdTime'>
                <#assign propertyNameColumn = "o.${field.propertyName}">
            <#--   重新赋值  -->
                <#if field.propertyName=='status'>
                    <#assign propertyNameColumn = 1>
                <#elseif field.propertyName=='lastUpdatedTime'>
                    <#assign propertyNameColumn = 'CURRENT_TIMESTAMP'>
                </#if>
                t.${field.name}=${propertyNameColumn} <#if field_index!=(table.fields?size - 1)>,</#if>
            </#if>
        </#list>
        WHEN NOT MATCHED THEN
        INSERT
        <trim prefix="(" suffix=")">
            <#list table.fields as field>
                ${field.name} <#if field_index!=(table.fields?size - 1)>,</#if>
            </#list>
        </trim>
        VALUES
        <trim prefix="(" suffix=")">
            <#list table.fields as field>
                <#assign propertyNameColumn = "o.${field.propertyName}">
                <#if field.keyFlag>
                    <#assign propertyNameColumn = "${tableSequence}.nextval">
                </#if>
                ${propertyNameColumn} <#if field_index!=(table.fields?size - 1)>,</#if>
            </#list>
        </trim>
    </insert>

    <!--批量插入/更新(根据索引条件merge into)-->
    <insert id="batchMergeByIndex">
        MERGE INTO ${table.name} t
        USING
        <trim prefix="(" suffix=")">
            <foreach collection="batchList" item="obj" separator="UNION ALL" open="" close="">
                SELECT
                    <#-- 字段属性 -->
                    <#assign text = '#\{'>
                    <#-- ----------  BEGIN 字段循环遍历  ---------->
                    <#list table.fields as field>
                    <#-- 展示非主键字段 -->
                        <#if !field.keyFlag>
                            <#assign propertyNameColumn = "${text} obj.${field.propertyName} }">
                        <#--   重新赋值  -->
                            <#if field.propertyName=='status'>
                                <#assign propertyNameColumn = 1>
                            <#elseif field.propertyName=='lastUpdatedTime'>
                                <#assign propertyNameColumn = 'CURRENT_TIMESTAMP'>
                            <#elseif field.propertyName=='createdTime'>
                                <#assign propertyNameColumn = 'CURRENT_TIMESTAMP'>
                            </#if>
                            ${propertyNameColumn} as ${field.propertyName} <#if field_index!=(table.fields?size - 1)>,</#if>
                        </#if>
                    </#list>
                    <#------------  END 字段循环遍历  ---------->
                from sys_dummy
            </foreach>
        </trim> AS o
        ON
        <trim prefix="(" suffix=")">
            <#list primaryKeys as field>
                <#list table.fields as field1>
                    <#if field == field1.name>
                        <#if field_index!=0>
                            AND
                        </#if>
                        t.${field1.name} = o.${field1.propertyName}
                    </#if>
                </#list>
            </#list>
            <#list table.fields as field1>
                <#if field1.propertyName=='status'>
                    AND
                    t.status != '9'
                </#if>
            </#list>
        </trim>
        WHEN MATCHED THEN
        UPDATE SET
            <#list table.fields as field>
            <#-- 展示非主键字段 -->
                <#if !field.keyFlag && field.propertyName != 'createdBy' && field.propertyName != 'createdByName' && field.propertyName != 'createdTime'>
                    <#assign propertyNameColumn = "o.${field.propertyName}">
                <#--   重新赋值  -->
                    <#if field.propertyName=='status'>
                        <#assign propertyNameColumn = 1>
                    <#elseif field.propertyName=='lastUpdatedTime'>
                        <#assign propertyNameColumn = 'CURRENT_TIMESTAMP'>
                    </#if>
                    t.${field.name}=${propertyNameColumn} <#if field_index!=(table.fields?size - 1)>,</#if>
                </#if>
            </#list>
        WHEN NOT MATCHED THEN
        INSERT
        <trim prefix="(" suffix=")">
            <#list table.fields as field>
                ${field.name} <#if field_index!=(table.fields?size - 1)>,</#if>
            </#list>
        </trim>
        VALUES
        <trim prefix="(" suffix=")">
            <#list table.fields as field>
                <#assign propertyNameColumn = "o.${field.propertyName}">
                <#if field.keyFlag>
                    <#assign propertyNameColumn = "${tableSequence}.nextval">
                </#if>
                ${propertyNameColumn} <#if field_index!=(table.fields?size - 1)>,</#if>
            </#list>
        </trim>
    </insert>

    <!--根据索引查询id(判断是否数据重复)-->
    <select id="selectIdsByIndex" resultType="java.lang.Long">
        SELECT id FROM ${table.name}
        WHERE
        <#assign text = '#\{'>
        <#list primaryKeys as field>
            <#list table.fields as field1>
                <#if field == field1.name>
                    <#if field_index!=0>
                        AND
                    </#if>
                    <#assign propertyNameColumn = "${text} ${field1.propertyName} }">
                    ${field1.name} = ${propertyNameColumn}
                </#if>
            </#list>
        </#list>
        <#list table.fields as field1>
            <#if field1.propertyName=='status'>
                AND
                status != '9'
            </#if>
        </#list>
    </select>

    <!--单条更新(根据id条件)-->
    <update id="updById">
        UPDATE ${table.name}
        <set>
            <#assign text = '#\{'>
            <#list table.fields as field>
            <#-- 展示非主键字段 -->
                <#if !field.keyFlag && field.propertyName != 'createdBy' && field.propertyName != 'createdByName' && field.propertyName != 'createdTime' && field.propertyName != 'status'>
                    <#assign propertyNameColumn = "${text} ${field.propertyName} }">
                    <#if field.propertyName=='lastUpdatedTime'>
                        <#assign propertyNameColumn = 'CURRENT_TIMESTAMP'>
                    </#if>
                    ${field.name}=${propertyNameColumn} <#if field_index!=(table.fields?size - 1)>,</#if>
                </#if>
            </#list>
        </set>
        <#assign id = '#\{'>
        WHERE
        <#list table.fields as field>
            <#if field.keyFlag>
                id=${id} ${field.propertyName} }
            </#if>
        </#list>
    </update>

    <!--查询已配置数据(支持字段模糊查询)-->
    <select id="selectConfigList" resultType="${package.Entity}.${entity}">
        SELECT
        <#list table.fields as field>
            ${field.name} <#if field_index!=(table.fields?size - 1)>,</#if>
        </#list>
        FROM ${table.name} WHERE 1=1
        <#list table.fields as field1>
            <#if field1.propertyName=='status'>
                AND
                status != '9'
            </#if>
        </#list>
        <#assign text = '#\{'>
        <choose>
            <when test="selectedIds!=null and selectedIds.size()>0">
                AND id IN
                <foreach collection="selectedIds" item="id" open="(" separator="," close=")">
                    ${text} id }
                </foreach>
            </when>
            <otherwise>
                <#list selectList as field>
                    <#list table.fields as field1>
                        <#if field == field1.name>
                            <#assign ifStart = "<if test=\"${field1.propertyName} !=null and ${field1.propertyName} != ''\">">
                            <#assign ifEnd = "</if>">
                            <#assign propertyNameColumn = "${text} ${field1.propertyName} }">
                            ${ifStart}
                                AND INSTR(lower(${field1.name}),lower(ltrim(rtrim(${propertyNameColumn}))))>0
                            ${ifEnd}
                        </#if>
                    </#list>
                </#list>
            </otherwise>
        </choose>
        <#list table.fields as field>
            <#if field.name=='CREATED_TIME'>
                ORDER BY ${field.name} desc NULLS LAST
            </#if>
        </#list>
    </select>

    <!--批量删除(根据id条件(将status改为9))-->
    <delete id="batchDelDataById" parameterType="com.taia.yms.entity.DeleteIdList">
        <#assign text = '#\{'>
        UPDATE ${table.name} SET status = '9', last_updated_by = ltrim(rtrim(${text} lastUpdatedBy })),
        last_updated_by_name = ltrim(rtrim(${text} lastUpdatedByName})), last_updated_time = now()
        <where>
            <choose>
                <when test="idList!=null and idList.size()>0">
                    id IN
                    <foreach collection="idList" item="id" open="(" separator="," close=")">
                        ${text} id }
                    </foreach>
                </when>
                <otherwise>
                    1 != 1
                </otherwise>
            </choose>
        </where>
    </delete>

</mapper>

自定义用于导入导出实体类

package ${package.Entity};

import cn.hutool.core.map.MapUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.taia.yms.fileutils3.constants.*;
import com.taia.yms.fileutils3.entity.*;
import com.taia.yms.fileutils3.filefactory.${superEntityClass};
import com.taia.yms.fileutils3.writer.ExcelDefaultWriteFile;
import java.util.Map;
/**
 * <p>
 * ${table.comment!}
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */

public class ${entity} extends AbstractDefaultSheetFactory {
    <#-- ----------  BEGIN 字段循环遍历  ---------->
    <#list fileFields as field>
        <#list table.fields as field1>
            <#if field == field1.name>
                private static final String ${field?upper_case} = "${field1.propertyName}";
            </#if>
        </#list>
    </#list>
    <#------------  END 字段循环遍历  ---------->


    @Override
    protected void setFileInfo(Map<String, Object> contextMap) {
        contextMap.put(FileUtilConstants.CONFIG_NAME, "${fileConfigName}");
    }

    @Override
    public void prepareOtherData(Map<String, Object> otherDataMap) {
        //TODO 根据实际情况调整
        String firstKey = MyFileUtils.concatStr(${fileFieldsStr?upper_case});
        otherDataMap.put(FileUtilConstants.SET_FIRST_KEY_STR, MapUtil.builder(firstKey, "${fileFieldsStr?upper_case}").build());
        otherDataMap.remove(FileUtilConstants.ROW_NUMBER);
    }

    @Override
    protected void setBasic(SheetInfo firstSheetInfo) {
        //TODO 根据实际情况调整
        firstSheetInfo.setCorRange("0#${fileFields?size -1}");
    }

    @Override
    protected void addNoteMap(Map<String, String> noteMap) {
        //TODO 根据实际情况调整
        <#-- ----------  BEGIN 字段循环遍历  ---------->
        <#list fileFields as field>
            noteMap.put(${field?upper_case}, MyFileUtils.getNote(true));
        </#list>
        <#------------  END 字段循环遍历  ---------->
    }

    @Override
    protected void addFirstHeadMap(Map<String, String> writeHeadMap) {
        //TODO 根据实际情况调整
        <#-- ----------  BEGIN 字段循环遍历  ---------->
        <#list fileFields as field>
            writeHeadMap.put(${field?upper_case}, "${field}");
        </#list>
        <#------------  END 字段循环遍历  ---------->
    }

    @Override
    protected void addFieldValidatorWrap(Map<String, FieldValidatorWrap> fieldValidatorWrapMap) {
        //TODO 根据实际情况调整
        <#-- ----------  BEGIN 字段循环遍历  ---------->
        <#list fileFields as field>
            fieldValidatorWrapMap.put(${field?upper_case}, getFiledWrap(false, 40, Regex.NAME_REGX));
        </#list>
        <#------------  END 字段循环遍历  ---------->
    }

    @Override
    protected void excelWritePostProcess(SheetInfo firstSheetInfo, ExcelDefaultWriteFile excelWriteFile) {
        ExcelWriter excelWriter = excelWriteFile.getExcelWriter();
        <#-- ----------  BEGIN 字段循环遍历  ---------->
        <#list 0..(fileFields!?size-1) as i>
            excelWriter.setColumnWidth(${i}, 20);
        </#list>
        <#------------  END 字段循环遍历  ---------->
    }
}

controller单元测试类

package ${package.Controller};

import cn.hutool.json.JSONUtil;
import com.taia.yms.YmsApplication;
import com.taia.yms.entity.reqbody.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import java.io.*;

@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@SpringBootTest(classes = YmsApplication.class)
@Slf4j
public class ${entity} extends ${superEntityClass}{
    private static final String IMPORT_TEMPLATE_FILE_NAME = "${processName} Config";

    @Test
    public void login(){
        log.info("登录token为:{}",token);
    }

    @Test
    public void save() throws Exception {
        ${reqBodyEntity} reqBody = new ${reqBodyEntity}();
        //todo

        String requestBody = JSONUtil.toJsonStr(reqBody);
        mockMvc.perform(
            MockMvcRequestBuilders.post("/${pathVersion}/${processName}/save")
            .contentType(MediaType.APPLICATION_JSON).content(requestBody)
            .header("Authorization",token)
        ).andDo(MockMvcResultHandlers.print());
    }

    @Test
    public void update() throws Exception {
        ${reqBodyEntity} reqBody = new ${reqBodyEntity}();
        //todo

        String requestBody = JSONUtil.toJsonStr(reqBody);
        mockMvc.perform(
        MockMvcRequestBuilders.post("/${pathVersion}/${processName}/save")
            .contentType(MediaType.APPLICATION_JSON).content(requestBody)
            .header("Authorization",token)
        ).andDo(MockMvcResultHandlers.print());
    }

    @Test
    public void delete() throws Exception {
        String ids = "1";

        mockMvc.perform(
            MockMvcRequestBuilders.get("/${pathVersion}/${processName}/delete?ids="+ids)
            .contentType(MediaType.APPLICATION_JSON)
            .header("Authorization",token)
        ).andDo(MockMvcResultHandlers.print());
    }

    @Test
    public void getList() throws Exception {
        ${pageReqBodyEntity} pageReqBody = new ${pageReqBodyEntity}();
        pageReqBody.setPageNum(1).setPageSize(10);

        mockMvc.perform(
            MockMvcRequestBuilders.post("/${pathVersion}/${processName}/getList")
            .contentType(MediaType.APPLICATION_JSON).content(JSONUtil.toJsonStr(pageReqBody))
            .header("Authorization",token)
        ).andDo(MockMvcResultHandlers.print());
    }

    @Test
    public void exportFile() throws Exception {
        ${pageReqBodyEntity} pageReqBody = new ${pageReqBodyEntity}();
        //导出数据
        pageReqBody.setIsExcel("1").setIsEmpty("0").setIsConfig("1");
        //导出模板
        //pageReqBody.setIsExcel("1").setIsEmpty("1").setIsConfig("1");

        String fileName = "0".equals(pageReqBody.getIsEmpty()) ? "exportFile": IMPORT_TEMPLATE_FILE_NAME;
        mockMvc.perform(
            MockMvcRequestBuilders.post("/${pathVersion}/${processName}/export")
            .contentType(MediaType.APPLICATION_JSON).content(JSONUtil.toJsonStr(pageReqBody))
            .header("Authorization",token)
        ).andDo(result -> {
            //保存为文件  文件目录需要自建
            File file  = new File(FILE_ROOT+"/${processName}/"+fileName+".xlsx");
            FileUtils.createParentDirectories(file);
            if(!file.exists()){
                file.createNewFile();
            }
        try(FileOutputStream fileOutputStream = new FileOutputStream(file)){
            IOUtils.write(result.getResponse().getContentAsByteArray(),fileOutputStream);
        }catch (IOException e){
            log.error("文件导出失败,异常信息:{}",e.getMessage());
        }
            //assert
            MatcherAssert.assertThat(file.exists(), Matchers.equalTo(true));
            MatcherAssert.assertThat(file.length(), Matchers.greaterThan(1024L));
        });
    }

    @Test
    public void importFile() throws Exception {
        //保存为文件  文件目录需要自建
        File file  = new File(FILE_ROOT+"/${processName}/"+IMPORT_TEMPLATE_FILE_NAME+".xlsx");
        ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/${pathVersion}/${processName}/import")
            .file(new MockMultipartFile("file", "${processName} Config.xlsx",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            new FileInputStream(file)))
            .header("Authorization",token)
        );
        MvcResult mvcResult = resultActions.andDo(MockMvcResultHandlers.print())
            .andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
        String result = new String(mvcResult.getResponse().getContentAsByteArray(),"UTF-8");
        log.info("==========结果为:{}==========" ,result);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱编程的Loren

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值