控制层

package ${package.Controller};
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import ${package.Service}.${table.serviceName};

@RestController
@RequestMapping("/${table.entityPath}")
public class ${table.controllerName} {

@Autowired
private ${table.serviceName} ${table.entityPath}Service;


/**
*
* @param id
* @param page 页数
* @param size 条数
* @return
*/

@ApiOperation(value = "自己填充", tags = {"自己填充", "自己填充"})
@RequestMapping(value = "/List", method = RequestMethod.GET)
public Result ${table.entityPath}List(
@RequestParam(name = "id", required = false) String id,
@RequestParam(required = true ,defaultValue = "1") int page,
@RequestParam( required = true) Integer size,defaultValue = "30") throws  Exception{
try {
return   Result.success(${table.entityPath}Service.find${entity}ByAll(null,page,size), ResultCode.成功.getCode());
} catch (Exception e) {
return   Result.error(ResultCode.失败.getMsg(),ResultCode.失败.getCode(),null);
}
}



@PreAuthorize("hasPermit('')")
@RequestMapping(value = "/id", method = RequestMethod.POST)
@ApiOperation(value = "详情", tags = {"详情", "自己填充"})
public Result  ${table.entityPath}Id(@RequestBody ${entity} ${table.entityPath})
throws  Exception{
try {
return   Result.success(${table.entityPath}Service.find${entity}Byid(${table.entityPath}.getId()), ResultCode.成功.getCode());
} catch (Exception e) {
return   Result.error(ResultCode.失败.getMsg(),ResultCode.失败.getCode(),null);
}
}


//    @PreAuthorize("hasPermit('')")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ApiOperation(value = "删除", tags = {"删除", "自己填充"})
public Result delete${entity}Id(@RequestBody ${entity} ${table.entityPath})
throws  Exception{
try {
${table.entityPath}Service.delete${entity}Byid(${table.entityPath}.getId());
return Result.success(ResultCode.成功, ResultCode.成功.getCode());

} catch (Exception e) {
return   Result.error(ResultCode.失败.getMsg(),ResultCode.失败.getCode(),null);
}
}



//    @PreAuthorize("hasPermit('')")
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ApiOperation(value = "更新", tags = {"更新/单个", "自己填充"})
public Result update${entity}Id(@RequestBody ${entity} ${table.entityPath})
throws  Exception{
try {
${table.entityPath}Service.update${entity}Byid(${table.entityPath});
return Result.success(ResultCode.成功, ResultCode.成功.getCode());
} catch (Exception e) {
return   Result.error(ResultCode.失败.getMsg(),ResultCode.失败.getCode(),null);
}
}


@RequestMapping(value = "/add", method = RequestMethod.POST)
@ApiOperation(value = "添加-单个", tags = {"添加-单个", "自己填充"})
public Result add${entity}Id(@RequestBody ${entity} ${table.entityPath})
throws  Exception{
try {
    ${table.entityPath}Service.add${entity}(${table.entityPath});
    return Result.success(ResultCode.成功, ResultCode.成功.getCode());
} catch (Exception e) {
return   Result.error(ResultCode.失败.getMsg(),ResultCode.失败.getCode(),null);
}
}


@RequestMapping(value = "/addBatch", method = RequestMethod.POST)
@ApiOperation(value = "添加-多个", tags = {"添加-多个", "自己填充"})
public Result add${entity}Batch(@RequestBody List<${entity}> ${table.entityPath})
throws  Exception{
try {
    ${table.entityPath}Service.add${entity}Batch(${table.entityPath});
    return Result.success(ResultCode.成功, ResultCode.成功.getCode());
} catch (Exception e) {
    return   Result.error(ResultCode.失败.getMsg(),ResultCode.失败.getCode(),null);
}
}

}

实体类

package ${package.Entity};

import java.io.Serializable;
import java.util.Date;
import com.theiavis.workhour.common.entity.BaseEntity;
import lombok.Getter;
import lombok.Setter;
<#list table.importPackages as pkg>
    <#if pkg == "java.util.Date">
        import ${pkg};
    </#if>
</#list>

/**
* ${table.name} : ${table.comment!}
*/
@Getter
@Setter
public class ${entity}  extends BaseEntity implements Serializable {

private static final long serialVersionUID = 1L;
<#-- ----------  属性私有化  ---------->
<#list table.fields as field>
    <#if field.keyFlag>
        <#assign keyPropertyName="${field.propertyName}"/>
    </#if>

    <#if field.keyFlag>
    <#-- 主键 -->
        /**
        * 主键 : ${field.name},  ${field.comment!}
        */
    <#-- 普通字段 -->
    <#elseif !field.keyFlag>
        /**
        * ${field.name},  ${field.comment!}
        */
    </#if>
<#-- 乐观锁注解 -->
    <#if (versionFieldName!"") == field.name>
        @Version
    </#if>
<#-- 逻辑删除注解 -->
    <#if (logicDeleteFieldName!"") == field.name>
        @TableLogic
    </#if>
    <#if field.propertyType == "LocalDateTime">
        private Date ${field.propertyName};
    </#if>
    <#if field.propertyType != "LocalDateTime">
        private ${field.propertyType} ${field.propertyName};
    </#if>
</#list>

<#------------  构造函数   ----------- -->
public ${entity}(<#list table.fields as field><#if field.propertyType == "LocalDateTime">Date ${field.propertyName}</#if><#if field.propertyType != "LocalDateTime">${field.propertyType} ${field.propertyName}</#if><#sep>,</#list>){
<#list table.fields as field>
    this.${field.propertyName} = ${field.propertyName};
</#list>
}

public ${entity}(){
}

<#------------  getter.setter封装  ---------->
<#if !entityLombokModel>
    <#list table.fields as field>
        <#if field.propertyType == "boolean">
            <#assign getprefix="is"/>
        <#else>
            <#assign getprefix="get"/>
        </#if>
        public <#if field.propertyType == "LocalDateTime">Date</#if><#if field.propertyType != "LocalDateTime">${field.propertyType}</#if> ${getprefix}${field.capitalName}() {
        return ${field.propertyName};
        }
        <#if entityBuilderModel>
            public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        <#else>
            public void set${field.capitalName}(<#if field.propertyType == "LocalDateTime">Date</#if><#if field.propertyType != "LocalDateTime">${field.propertyType}</#if> ${field.propertyName}) {
        </#if>
        this.${field.propertyName} = ${field.propertyName};
        <#if entityBuilderModel>
            return this;
        </#if>
        }
    </#list>
</#if>

<#-------------  重写toString()  ----------------->
<#if !entityLombokModel>
    @Override
    public String toString() {
    return "${entity}{" +
    <#list table.fields as field>
        <#if field_index==0>
            "${field.propertyName}=" + ${field.propertyName} +
        <#else>
            ", ${field.propertyName}=" + ${field.propertyName} +
        </#if>
    </#list>
    "}";
    }
</#if>
}

持久层mapper.java

package ${package.Mapper};

import ${package.Entity}.${entity};
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

public interface ${table.mapperName} extends BaseMapper<${entity}>{

/**
*  查询表${table.name}所有信息
*/
<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据${entity}属性查询表${table.name}信息
        *  @param  ${table.entityPath}
        */
    List<${entity}>  find${entity}ByAll(@Param("${table.entityPath}") ${entity} ${table.entityPath} ,Page<${entity}> page,Integer size,Integer pageSize) ;
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据${entity}属性查询表${table.name}信息
        *  @param  ${table.entityPath}
        */
        ${entity} find${entity}Count(@Param("${table.entityPath}") ${entity} ${table.entityPath}) ;
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}查询表${table.name}信息
        *  @param ${field.propertyName}
        */
       ${entity} find${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}查询表${table.name}信息
        *  @param ${field.propertyName}
        */
        void delete${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
    </#if>
</#list>

<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}更新表${table.name}信息
        *  @param ${table.entityPath}
        */
        void update${entity}By${field.propertyName}(@Param("${table.entityPath}") ${entity} ${table.entityPath});
    </#if>
</#list>

<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  新增表${table.name}信息
        *  @param ${table.entityPath}
        */
        void add${entity}(@Param("${table.entityPath}") ${entity} ${table.entityPath});
    </#if>
</#list>
}

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}">

    <!-- 通用设置 -->

        <!-- 通用查询列 -->
        <sql id="Base_Column_List">
            <#list table.fields as field>
                <#if field_index gt 0>,</#if>a.${field.name}
            </#list>
        </sql>
    <#if baseColumnList>


        <!-- 通用设置列 -->
        <sql id="${entity}SetColumns">
            <#list table.commonFields as field><#--生成公共字段-->
                <if test="${field.propertyName}!=null ">
                    ${field.name} = ${r"#{"}${table.entityPath}.${field.propertyName}${r"}"},
                </if>
            </#list>
            <#list table.fields as field>
                <#if !field.keyFlag><#--生成普通字段 -->
                    <if test="${field.propertyName}!=null ">
                        ${field.name} = ${r"#{"}${table.entityPath}.${field.propertyName}${r"}"},
                    </if>
                </#if>
            </#list>
        </sql>
    </#if>

    <#if baseResultMap>
        <!-- 通用查询映射结果 -->
        <resultMap id="${entity}Map" 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>
    </#if>
    <#list table.fields as field>
        <#if field.keyFlag>
            <!-- 根据{entity}属性查询表${table.name}信息 -->
            <select id="find${entity}ByAll" resultType="${package.Entity}.${entity}">
                SELECT
                <include refid="Base_Column_List"/>
                FROM ${table.name} AS a
                where

                <if test="${table.entityPath}!=null  and ${table.entityPath}.${field.propertyName} !=null and ${table.entityPath}.${field.propertyName} !=''">a.${field.propertyName}=${r"#{"} ${table.entityPath}.${field.propertyName} ${r"}"} and</if>
                a.${field.name}
                limit ${r"#{"}size${r"}"},${r"#{"}pageSize${r"}"}
            </select>
        </#if>
    </#list>



    <#list table.fields as field>
        <#if field.keyFlag>
            <!-- 根据{entity}属性查询表${table.name}信息 -->
         <select id="find${entity}Count" resultType="${package.Entity}.${entity}">
            SELECT
            count(${field.name}) AS countPageSize
            FROM ${table.name}
         </select>
        </#if>
    </#list>



    <#list table.fields as field>
        <#if field.keyFlag>
            <!-- 根据主键${field.propertyName}查询表${table.name}信息 -->
            <select id="find${entity}By${field.propertyName}" resultType="${package.Entity}.${entity}">
                SELECT
                <include refid="Base_Column_List"/>
                FROM ${table.name} AS a
                WHERE a.${field.name}=${r"#{"}${field.propertyName}${r"}"}
            </select>
        </#if>
    </#list>



    <#list table.fields as field>
        <#if field.keyFlag>
            <!-- 根据主键${field.propertyName}删除表${table.name}信息 -->
            <delete id="delete${entity}By${field.propertyName}">
                DELETE FROM
                ${table.name}
                WHERE  ${field.name}=${r"#{"}${field.propertyName}${r"}"}
            </delete>
        </#if>
    </#list>

    <#list table.fields as field>
        <#if field.keyFlag>
            <!-- 根据主键${field.propertyName}更新表${table.name}信息 -->
            <update id="update${entity}By${field.propertyName}" parameterType="${package.Entity}.${entity}">
                UPDATE ${table.name}
                set
                <trim suffixOverrides="," >
                <#list table.fields as field>
                    <#if field_index gt 0 ></#if><if test="${table.entityPath}.${field.propertyName} !=null  and ${table.entityPath}.${field.propertyName} !=''"> ${field.name}=${r"#{"}${table.entityPath}.${field.propertyName}${r"}"},</if>

                    </#list>
                </trim>
                WHERE
                <#list table.fields as field><#if field.keyFlag>${field.name}=${r"#{"}${table.entityPath}.${field.propertyName}${r"}"}</#if></#list>
            </update>
        </#if>
    </#list>

    <#list table.fields as field>
        <#if field.keyFlag>
            <!-- 新增表${table.name}信息 -->
            <insert id="add${entity}">
                INSERT INTO ${table.name}
                <trim suffixOverrides="," suffix=")" prefix="(">
                <#list table.fields as field>
                    <#if field_index gt 0  ></#if><if test="${table.entityPath}.${field.propertyName} !=null "> ${field.name},</if>
                </#list>
                </trim>
                <trim suffixOverrides="," suffix=")" prefix="values (">
                <#list table.fields as field>
                    <#if field_index gt 0></#if><if test="${table.entityPath}.${field.propertyName} !=null "> ${r"#{"}${table.entityPath}.${field.propertyName}${r"}"},</if>
                </#list>
                </trim>
            </insert>
        </#if>
    </#list>



</mapper>

service层

package ${package.Service};

import ${package.Entity}.${entity};
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;

public interface ${table.serviceName}{
<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据${entity} 属性查询表${table.name}信息
        *  @param${entity}
        */
    IPage<${entity}>  find${entity}ByAll(${entity} ${table.entityPath},Integer size,Integer pageSize);
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据${entity} 属性查询表总条数信息
        *  @param${entity}
        */
        ${entity}  find${entity}Count(${entity} ${table.entityPath});
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}更新表${table.name}信息
        *  @param ${field.propertyName}
        */
        ${entity} find${entity}By${field.propertyName}( ${field.propertyType}  ${field.propertyName});
    </#if>
</#list>



<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}查询表${table.name}信息
        *  @param ${field.propertyName}
        */
        void delete${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}查询表${table.name}信息
        *  @param ${field.propertyName}
        */
        void delete${entity}ByBatch(List<${field.propertyType}> ${field.propertyName});
    </#if>
</#list>



<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}更新表${table.name}信息
        *  @param ${table.entityPath}
        */
        void update${entity}By${field.propertyName}(${entity} ${table.entityPath});
    </#if>
</#list>



<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}更新表${table.name}信息
        *  @param ${table.entityPath}
        */
         void find${entity}ByBatch(List<${entity}> ${table.entityPath});
    </#if>
</#list>

<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}更新表${table.name}信息
        *  @param ${table.entityPath}
        */
        void update${entity}ByBatch(List<${entity}> ${table.entityPath});
    </#if>
</#list>




<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  新增表${table.name}信息
        *  @param ${table.entityPath}
        */
        void add${entity}(${entity} ${table.entityPath});
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  新增表${table.name}信息
        *  @param ${table.entityPath}
        */
        void add${entity}Batch(List<${entity}> ${table.entityPath});
    </#if>
</#list>

}

serviceImpl

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;

@Service
public class ${table.serviceImplName} implements ${table.serviceName} {

@Autowired
private ${table.mapperName} ${table.entityPath}Mapper;





<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据${entity}属性查询表${table.name}信息
        *  @param ${table.entityPath}
        */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public IPage<${entity}> find${entity}ByAll(${entity} ${table.entityPath},Integer size,Integer pageSize)
        {
        Page<${entity}> page =new Page<>();
        page.setRecords(${table.entityPath}Mapper.find${entity}ByAll(${table.entityPath},null,new BaseEntity().getTotalSize(size,pageSize),pageSize));
        page.setTotal(${table.entityPath}Mapper.find${entity}Count(${table.entityPath}).getCountPageSize());
        return page;
        }
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}查询表${table.name}信息
        *  @param ${table.entityPath}
        */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public ${entity} find${entity}Count(${entity} ${table.entityPath})
        {
        return ${table.entityPath}Mapper.find${entity}Count(${table.entityPath});

        }
    </#if>
</#list>




<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}查询表${table.name}信息
        *  @param ${field.propertyName}
        */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public ${entity} find${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName}) {
        return ${table.entityPath}Mapper.find${entity}By${field.propertyName}(${field.propertyName});
        }

    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}查询表${table.name}信息
        *  @param ${field.propertyName}
        */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void delete${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName}) {
         ${table.entityPath}Mapper.delete${entity}By${field.propertyName}(${field.propertyName});
        }
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}查询表${table.name}信息
        *  @param ${field.propertyName}
        */
        /*     @Override
        @Transactional(rollbackFor = Exception.class)
        public void delete${entity}ByBatch(List<${field.propertyType}> ${field.propertyName}) {
         QueryWrapper queryWrapper =new QueryWrapper();
         queryWrapper.in("条件字段",${field.propertyName});

         ${table.entityPath}Mapper.delete(queryWrapper);
        }
        */
    </#if>
</#list>







<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}更新表${table.name}信息
        *  @param ${table.entityPath}
        */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void update${entity}By${field.propertyName}(${entity} ${table.entityPath}) {
         ${table.entityPath}Mapper.update${entity}By${field.propertyName}(${table.entityPath});
        }
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}更新表${table.name}信息
        *  @param ${table.entityPath}
        */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void find${entity}ByBatch(List<${entity}> ${table.entityPath})
        {
       /*
        ArrayList arrayList=new ArrayList<>();
        ${table.entityPath}.stream().forEach(i->arrayList.add( i.主键属性/条件字段));
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.in("条件字段",arrayList);
         ${table.entityPath}Mapper.selectList(queryWrapper);
        */
        }
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  根据主键${field.propertyName}更新表${table.name}信息
        *  @param ${table.entityPath}
        */
    /*    @Override
        @Transactional(rollbackFor = Exception.class)
        public void update${entity}ByBatch(List<${entity}> ${table.entityPath})
        {
        ${table.entityPath}.stream().forEach(i->{
        UpdateWrapper<${entity}> ${table.entityPath}UpdateWrapper=new UpdateWrapper<>();
        ${table.entityPath}UpdateWrapper.eq("条件字段","i.条件属性");
        ${table.entityPath}Mapper.update(i,${table.entityPath}UpdateWrapper);
    });
        }*/
    </#if>
</#list>





<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  新增表${table.name}信息
        *  @param ${table.entityPath}
        */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void add${entity}(${entity} ${table.entityPath}) {
         ${table.entityPath}Mapper.add${entity}(${table.entityPath});
        }
    </#if>
</#list>


<#list table.fields as field>
    <#if field.keyFlag>
        /**
        *  新增表${table.name}信息
        *  @param ${table.entityPath}
        */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void add${entity}Batch(List<${entity}> ${table.entityPath}) {
            ${table.entityPath}.stream().forEach(cm->{
            ${table.entityPath}Mapper.insert(cm);
        });
}



    </#if>
</#list>

}

依赖类含limit分页

package com.theiavis.workhour.common.entity;

import lombok.*;

@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class BaseEntity {


    //第条数
    private  Integer size;
    //第页数
    private  Integer page;
    //总页数
    private Integer countPage;
    //总条数
    private Integer countPageSize;


/**
处理页数size,pageSize条数
 */
public Integer getTotalSize(int size ,int pageSize){

    if (size !=1&&size!=0){

        return  (size -1)*pageSize +1;
    }else{

        return  pageSize;
    }

}


    /**
     处理页数size,pageSize条数
     */
    public Integer getTotalPage(int size){
            return  size+1;
        }



}

生成器

package com.alibaba.generatorCode;



import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 集成代码生成器,可定义路径到项目包,直接生成到项目中,注意bean需要和xml同步属性不然会插入不了
 *
 * @author lyh
 * @since 2021-12-01
 * @deprecated 例如钉钉生成的路径下的包
 */
public class GeneratorCode {

    private static final Logger logger = LoggerFactory.getLogger(GeneratorCode.class);
    private static Pattern UNDERLINE_PATTERN = Pattern.compile("_([a-z])");
    public static String path = "C:\\Users\\dell G3-5\\Desktop\\jeecg-boot-master\\alibaba\\chatgpt\\";//可以根据情况改项目路径
    public static String moduleName;
    public static String parent="com.alibaba.demo.";
    public static String mysqlLink = "jdbc:mysql://localhost:3306/chatgpt?useUnicode=true&autoReconnect=true&failOverReadOnly=false&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
    public static String root = "root";
    public static String password = "root";
    public static String mysqlName = "chatgpt";


    public static void main(String[] args) throws Exception {
        ArrayList<String> tableNames=getAllTableNames();
        for (int i=0; i<=tableNames.size();i++){
            Generator(tableNames.get(i));
        }



    }


    private static void Generator(String tableName){
        // 配置模板
        new TemplateConfig.Builder().serviceImpl("/templates/serviceImpl.java");
        FastAutoGenerator.create( mysqlLink,
                root,
                password)

                // 全局配置,生成的代码路径
//                .globalConfig.setDateType(DateType.ONLY_DATE)
                .globalConfig((scanner, builder) ->
                        builder.author("lyh").fileOverride().outputDir(path))
                // 包配置
                .templateEngine(new FreemarkerTemplateEngine())
                .packageConfig((scanner, builder) -> builder.parent(parent + underlineToHump(tableName))//配置包路径
                        .entity("bean")
                        .service("service")
                        .pathInfo(Collections.singletonMap(OutputFile.serviceImpl,
                                path + "com\\service\\impl"))
                        .controller("controller")
                        .mapper("mapper")
                        .xml("mapper")
                        .pathInfo(Collections.singletonMap(OutputFile.mapperXml,
                                path + "com\\resources\\mybatis\\mapper\\" + underlineToHump(tableName) + "\\"))
                )
                // 策略配置

                .strategyConfig((scanner, builder) -> builder.addInclude(getTables(tableName))
                        .controllerBuilder().enableRestStyle().enableHyphenStyle()
                        .entityBuilder().enableLombok().disableSerialVersionUID().addTableFills(
                                new Column("create_time", FieldFill.INSERT)
                        ).build())

                .execute();
        new InjectionConfig.Builder()

                .beforeOutputFile((tableInfo, objectMap) -> {
                    System.out.println("tableInfo: " + tableInfo.getEntityName() + " objectMap: " + objectMap.size());
                })
                .customFile(Collections.singletonMap("mapper.xml", "/templates/mapper.xml.ftl"))
                .customFile(Collections.singletonMap("bean.java", "/templates/bean.java.ftl"))
                .customFile(Collections.singletonMap("service.java", "/templates/service.java.ftl"))
                .customFile(Collections.singletonMap("serviceImpl.java", "/templates/serviceImpl.java.ftl"))
                .customFile(Collections.singletonMap("mapper.java", "/templates/mapper.java.ftl"))
                .build();

    }

    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }


    /**
     * 根据传入的带下划线的字符串转化为驼峰格式
     *
     * @param str
     * @return
     * @author mrf
     */

    public static String underlineToHump(String str) {
        //正则匹配下划线及后一个字符,删除下划线并将匹配的字符转成大写
        Matcher matcher = UNDERLINE_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer(str);
        if (matcher.find()) {
            sb = new StringBuffer();
            //将当前匹配的子串替换成指定字符串,并且将替换后的子串及之前到上次匹配的子串之后的字符串添加到StringBuffer对象中
            //正则之前的字符和被替换的字符
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
            //把之后的字符串也添加到StringBuffer对象中
            matcher.appendTail(sb);
        } else {
            //去除除字母之外的前面带的下划线
            return sb.toString().replaceAll("_", "");
        }
        return underlineToHump(sb.toString());
    }

    protected static String getModuleName() {
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入模块名称或者表名:");
        moduleName = scan.next();
        return moduleName;
    }


    /**
     * 获取指定数据库和用户的所有表名
     *
     * @return
     * @throws Exception
     */
    private static ArrayList<String> getAllTableNames() throws Exception {
        ArrayList<String> arrayList =new ArrayList<>();
        Connection conn = null;
        ResultSet resultSet = null;
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                conn = (Connection) DriverManager.getConnection(mysqlLink, root, password);
            } catch (Exception e) {
                System.out.println(e.toString());
            }

            Statement statement=conn.createStatement();
            String sql= new StringBuilder().append("SELECT TABLE_NAME").append("  from information_schema.`TABLES` WHERE TABLE_SCHEMA='").append(mysqlName).append("'").toString();
            logger.info("执行的sql是"+sql);
             resultSet=statement.executeQuery(sql);
            while (resultSet.next()) {
                arrayList.add(resultSet.getString(1));
            System.out.println(resultSet.getString(1));
        }
        return arrayList;
    }
}
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐