0


工具—IDEA代码自动生成插件EasyCode

简介

官网简介

  • 基于IntelliJ IDEA开发的代码生成插件,支持自定义任意模板(Java,html,js,xml)。
  • 只要是与数据库相关的代码都可以通过自定义模板来生成。支持数据库类型与java类型映射关系配置。
  • 支持同时生成生成多张表的代码。每张表有独立的配置信息。完全的个性化定义,规则由你设置。

背景

枯燥繁琐的CRUD,不如自动生成自己喜欢的代码风格

教程

一、 安装

pom依赖

<!--JSON工具--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.30</version></dependency><!--validation校验工具--><dependency><groupId>javax.validation</groupId><artifactId>validation-api</artifactId><version>${validation.version}</version></dependency><!--lombok工具--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--hutool工具--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>4.4.5</version></dependency><!--mybatis-plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>3.5.1</version></dependency>

1、安装EasyCode插件

EasyCode插件安装

二、 配置代码模板

模板配置路径
模板配置路径

1、Type Mapper类型映射

根据自己实际情况对应数据表结构类型与Java类型
Type Mapper类型映射

2、Template代码模板

这里使用的是默认模板Defaul,可保留原插件默认模板,新建自己Group Name组名
新建模板组名

2.1、Template代码模板:controller.java.vm
##引入宏定义
$!{define.vm}

##定义初始变量
#set($controllerName = $tool.append($tableInfo.name,"Controller"))
##实体类名
#set($entityName = $tool.append($tableInfo.name,"Entity"))
#set($queryPage = $tool.append("query", $tableInfo.name,"Page"))
#set($queryList = $tool.append("query", $tableInfo.name,"List"))
#set($queryById = $tool.append("query", $tableInfo.name,"ById"))
#set($save = $tool.append("save", $tableInfo.name))
#set($update = $tool.append("update", $tableInfo.name))
#set($delete = $tool.append("delete", $tableInfo.name,"ById"))

##设置回调
$!callback.setFileName($tool.append($controllerName,".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.$entityName;import $!{tableInfo.savePackageName}.service.${tableInfo.name}Service;importcom.alibaba.fastjson2.JSON;importcom.baomidou.mybatisplus.extension.plugins.pagination.Page;importcom.clancy.common.constants.R;importorg.springframework.web.bind.annotation.*;importlombok.extern.slf4j.Slf4j;importcn.hutool.core.collection.CollUtil;importcn.hutool.core.util.ObjectUtil;importjavax.annotation.Resource;importjavax.validation.Valid;importjava.util.List;importjava.util.Map;

##使用宏定义实现类注释信息
#tableComment("控制层")@Slf4j@RestController@RequestMapping("/$!tool.firstLowerCase($tableInfo.name)")publicclass $!{controllerName}{/**
     * 服务对象
     */@Resourceprivate ${tableInfo.name}Service $!tool.firstLowerCase(${tableInfo.name})Service;/**
     * 查询${tableInfo.comment}分页列表
     * @param current 当前页码
     * @param size 每页页数
     * @param params 筛选条件
     * @return 分页列表
     */@GetMapping("$queryPage")publicR $queryPage(@RequestParam(defaultValue ="1")long current,@RequestParam(defaultValue ="20")long size,Map<String,Object> params){try{
            log.info("查询${tableInfo.comment}分页列表入参current:{},size:{},params:{}",JSON.toJSONString(current),JSON.toJSONString(size),JSON.toJSONString(params));Page<$entityName> page = $!tool.firstLowerCase(${tableInfo.name})Service.$queryPage(current, size, params);
            log.info("查询${tableInfo.comment}分页列表出参:{}",JSON.toJSONString(page));returnR.success("查询${tableInfo.comment}分页列表成功", page);}catch(Exception e){
            log.info("查询${tableInfo.comment}分页列表异常:{}\n{}", e.getMessage(), e);returnR.failed("查询${tableInfo.comment}分页列表异常:"+  e.getMessage());}}/**
     * 查询${tableInfo.comment}列表
     * @param params 筛选条件
     * @return 列表
     */@GetMapping("$queryList")publicR $queryList(@RequestParamMap<String,Object> params){try{
            log.info("查询${tableInfo.comment}列表入参:{}",JSON.toJSONString(params));List<$entityName> list = $!tool.firstLowerCase(${tableInfo.name})Service.$queryList(params);
            log.info("查询${tableInfo.comment}列表出参:{}",JSON.toJSONString(list));if(CollUtil.isEmpty(list)){returnR.success("查询${tableInfo.comment}列表为空");}returnR.success("查询${tableInfo.comment}列表成功", list);}catch(Exception e){
            log.error("查询${tableInfo.comment}列表异常:{}\n{}", e.getMessage(), e);returnR.failed("查询${tableInfo.comment}列表异常:"+ e.getMessage());}}/**
     * 通过主键查询${tableInfo.comment}详情
     * @param id 主键
     * @return ${tableInfo.comment}
     */@GetMapping("{id}")publicR $queryById(@PathVariable("id") $!pk.shortType id){try{
            log.info("查询${tableInfo.comment}详情入参:{}",JSON.toJSONString(id));
            $entityName $!{tool.firstLowerCase($entityName)}= $!tool.firstLowerCase(${tableInfo.name})Service.$queryById(id);
            log.info("查询${tableInfo.comment}详情出参:{}",JSON.toJSONString($!{tool.firstLowerCase($entityName)}));if(ObjectUtil.isNull($!{tool.firstLowerCase($entityName)})){returnR.success("查询${tableInfo.comment}详情为空");}returnR.success("查询${tableInfo.comment}详情成功", $!{tool.firstLowerCase($entityName)});}catch(Exception e){
            log.error("查询${tableInfo.comment}详情异常:{}\n{}", e.getMessage(), e);returnR.failed("查询${tableInfo.comment}详情异常:"+ e.getMessage());}}/**
     * 保存${tableInfo.comment}
     * @param $!{tool.firstLowerCase($entityName)} 筛选条件
     * @return 成功标志位
     */@PostMappingpublicR $save(@RequestBody@Valid $entityName $!{tool.firstLowerCase($entityName)}){try{
            log.info("保存${tableInfo.comment}入参:{}",JSON.toJSONString($!{tool.firstLowerCase($entityName)}));Boolean flag = $!tool.firstLowerCase(${tableInfo.name})Service.$save($!{tool.firstLowerCase($entityName)});
            log.info("保存${tableInfo.comment}出参:{}",JSON.toJSONString(flag));if(flag){returnR.success("保存${tableInfo.comment}成功");}returnR.failed("保存${tableInfo.comment}失败");}catch(Exception e){
            log.error("保存${tableInfo.comment}异常:{}\n{}", e.getMessage(), e);returnR.failed("保存${tableInfo.comment}异常:"+ e.getMessage());}}/**
     * 更新${tableInfo.comment}
     * @param $!{tool.firstLowerCase($entityName)} 筛选条件
     * @return 成功标志位
     */@PutMappingpublicR $update(@RequestBody@Valid $entityName $!{tool.firstLowerCase($entityName)}){try{
            log.info("更新${tableInfo.comment}入参:{}",JSON.toJSONString($!{tool.firstLowerCase($entityName)}));Boolean flag = $!tool.firstLowerCase(${tableInfo.name})Service.$update($!{tool.firstLowerCase($entityName)});
            log.info("更新${tableInfo.comment}出参:{}",JSON.toJSONString(flag));if(flag){returnR.success("更新${tableInfo.comment}成功");}returnR.failed("更新${tableInfo.comment}失败");}catch(Exception e){
            log.error("更新${tableInfo.comment}异常:{}\n{}", e.getMessage(), e);returnR.failed("更新${tableInfo.comment}异常:"+ e.getMessage());}}/**
     * 删除${tableInfo.comment}
     * @param id 主键id
     * @return 成功标志位
     */@DeleteMappingpublicR $delete($!pk.shortType id){try{
            log.info("删除${tableInfo.comment}入参:{}",JSON.toJSONString(id));Boolean flag = $!tool.firstLowerCase(${tableInfo.name})Service.$delete(id);
            log.info("删除${tableInfo.comment}出参:{}",JSON.toJSONString(flag));if(flag){returnR.success("删除${tableInfo.comment}成功");}returnR.failed("删除${tableInfo.comment}失败");}catch(Exception e){
            log.error("删除${tableInfo.comment}异常:{}\n{}", e.getMessage(), e);returnR.failed("删除${tableInfo.comment}异常:", e.getMessage());}}}
2.2、Template代码模板:dao.java.vm
##引入宏定义
$!{define.vm}

##定义初始变量
#set($tableName = $tool.append($tableInfo.name,"Dao"))
##实体类名
#set($entityName = $tool.append($tableInfo.name,"Entity"))
##设置回调
$!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.$entityName;importcom.baomidou.mybatisplus.core.mapper.BaseMapper;importorg.springframework.stereotype.Repository;

##使用宏定义实现类注释信息
#tableComment("数据访问层")@Repositorypublicinterface $!{tableName}extendsBaseMapper<$entityName>{}
2.3、Template代码模板:entity.java.vm
##引入宏定义
$!{define.vm}
$!{init.vm}

##定义初始变量
##类名
#set($tableName = $tool.append($tableInfo.name,"Entity"))
##包名
#set($packageName ="entity")

##设置回调
$!callback.setFileName($tool.append($tableName,".java"))
$!callback.setSavePath($tool.append($tableInfo.savePath,"/", $packageName))

##设置包名
#if($tableInfo.savePackageName)package $!{tableInfo.savePackageName}.#{end}$packageName;

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

##使用全局变量实现默认包导入
$!{autoImport.vm}importlombok.Data;importjava.io.Serializable;importcom.baomidou.mybatisplus.annotation.*;

##使用宏定义实现类注释信息
#tableComment("实体类")@Data@TableName("$!{tableInfo.obj.name}")publicclass $tableName extendsBaseEntityimplementsSerializable{privatestaticfinallong serialVersionUID = $!tool.serial();
#foreach($column in $tableInfo.fullColumn)
#if(${column.comment})/**
    * ${column.comment}
    */
#end
#if($pk.name == $!{column.name})@TableId(value ="$pk.obj.name", type =IdType.AUTO)
#end
    private $!{tool.getClsNameByFullName($column.type)} $!{column.name};

#end
}
2.4、Template代码模板:mapper.xml.vm
##引入mybatis支持
$!{mybatisSupport.vm}
$!{init.vm}

##定义初始变量
##实体类名
#set($entityName = $tool.append($tableInfo.name,"Entity"))
#set($queryPage = $tool.append("query", $tableInfo.name,"Page"))
#set($queryList = $tool.append("query", $tableInfo.name,"List"))
#set($queryById = $tool.append("query", $tableInfo.name,"ById"))
#set($insert = $tool.append("insert", $tableInfo.name))
#set($update = $tool.append("update", $tableInfo.name))
#set($delete = $tool.append("delete", $tableInfo.name,"ById"))

##设置保存名称与保存位置
$!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}.dao.$!{tableInfo.name}Dao"><resultMap type="$!{tableInfo.savePackageName}.entity.${entityName}" id="$!{tableInfo.name}Map">
#foreach($column in $tableInfo.fullColumn)<result property="$!column.name" column="$!column.obj.name" jdbcType="$!column.ext.jdbcType"/>
#end
    </resultMap><!-- 基础sql --><sql id="baseSql">
        #allSqlColumn(), del_flg, create_id, update_id, create_time, update_time, remark
    </sql><!--查询${tableInfo.comment}分页列表--><select id="$queryPage" resultMap="$!{tableInfo.name}Map">
        select
          <include refid="baseSql"/>
        from $!tableInfo.obj.name
        <where>
            del_flg =0
#foreach($column in $tableInfo.fullColumn)<if test="params.$!column.name != null#if($column.type.equals("java.lang.String")) and params.$!column.name != ''#end">
                and $!column.obj.name = #{params.$!column.name}</if>
#end
            <if test="params.createId != null">
                and create_id = #{params.createId}</if><if test="params.updateId != null">
                and update_id = #{params.updateId}</if><if test="params.createBeginTime != null">
                and create_time &gt;= #{params.createBeginTime}</if><if test="params.createEndTime != null">
                and create_time &lt;= #{params.createEndTime}</if><if test="params.updateBeginTime != null">
                and update_time &gt;= #{params.updateBeginTime}</if><if test="params.updateEndTime != null">
                and update_time &gt;= #{params.updateEndTime}</if><if test="params.remark != null and params.remark != ''">
                and remark like concat('%',#{params.remark},'%')</if></where>
        order by
        <choose><when test="params.field != null and params.field != '' and params.order != null and params.order != ''">
                #{params.field} #{params.order}</when><otherwise>
                update_time desc
            </otherwise></choose></select><!--查询${tableInfo.comment}列表--><select id="$queryList" resultMap="$!{tableInfo.name}Map">
        select
          <include refid="baseSql"/>
        from $!tableInfo.obj.name
        <where>
            del_flg =0
#foreach($column in $tableInfo.fullColumn)<if test="params.$!column.name != null#if($column.type.equals("java.lang.String")) and params.$!column.name != ''#end">
                and $!column.obj.name = #{params.$!column.name}</if>
#end
            <if test="params.createId != null">
                and create_id = #{params.createId}</if><if test="params.updateId != null">
                and update_id = #{params.updateId}</if><if test="params.createBeginTime != null">
                and create_time &gt;= #{params.createBeginTime}</if><if test="params.createEndTime != null">
                and create_time &lt;= #{params.createEndTime}</if><if test="params.updateBeginTime != null">
                and update_time &gt;= #{params.updateBeginTime}</if><if test="params.updateEndTime != null">
                and update_time &gt;= #{params.updateEndTime}</if><if test="params.remark != null and params.remark != ''">
                and remark like concat('%',#{params.remark},'%')</if></where>
        order by
        <choose><when test="params.field != null and params.field != '' and params.order != null and params.order != ''">
                #{params.field} #{params.order}</when><otherwise>
                update_time desc
            </otherwise></choose></select><!--通过主键查询${tableInfo.comment}--><select id="$queryById" resultMap="$!{tableInfo.name}Map">
        select
          <include refid="baseSql"/>
        from $!tableInfo.obj.name
        where $!pk.obj.name = #{$!pk.name}</select><!--新增${tableInfo.comment}--><insert id="$insert" keyProperty="$!pk.name" useGeneratedKeys="true" parameterType="$!{tableInfo.savePackageName}.entity.${entityName}">
        insert into $!{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><!--通过主键修改${tableInfo.comment}--><update id="$update" parameterType="$!{tableInfo.savePackageName}.entity.${entityName}">
        update $!{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><!--通过主键删除${tableInfo.comment}--><delete id="$delete">
        update $!{tableInfo.obj.name} set del_flg =0 where $!pk.obj.name = #{$!pk.name}</delete><!--统计总行数--><select id="count" resultType="java.lang.Long">
        select count(1)
        from $!tableInfo.obj.name
        <where>
            del_flg =0
#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="insertBatch" keyProperty="$!pk.name" useGeneratedKeys="true">
        insert into $!{tableInfo.obj.name}(#foreach($column in $tableInfo.otherColumn)$!column.obj.name#if($velocityHasNext), #end#end)
        values
        <foreach collection="entities" item="entity" separator=",">(#foreach($column in $tableInfo.otherColumn)#{entity.$!{column.name}}#if($velocityHasNext), #end#end)</foreach></insert><insert id="insertOrUpdateBatch" keyProperty="$!pk.name" useGeneratedKeys="true">
        insert into $!{tableInfo.obj.name}(#foreach($column in $tableInfo.otherColumn)$!column.obj.name#if($velocityHasNext), #end#end)
        values
        <foreach collection="entities" item="entity" separator=",">(#foreach($column in $tableInfo.otherColumn)#{entity.$!{column.name}}#if($velocityHasNext), #end#end)</foreach>
        on duplicate key update
        #foreach($column in $tableInfo.otherColumn)$!column.obj.name =values($!column.obj.name)#if($velocityHasNext),
        #end#end

    </insert></mapper>
2.5、Template代码模板:service.java.vm
##引入宏定义
$!{define.vm}

##定义初始变量
#set($serviceName = $tool.append($tableInfo.name,"Service"))
##实体类名
#set($entityName = $tool.append($tableInfo.name,"Entity"))
#set($queryPage = $tool.append("query", $tableInfo.name,"Page"))
#set($queryList = $tool.append("query", $tableInfo.name,"List"))
#set($queryById = $tool.append("query", $tableInfo.name,"ById"))
#set($save = $tool.append("save", $tableInfo.name))
#set($update = $tool.append("update", $tableInfo.name))
#set($delete = $tool.append("delete", $tableInfo.name,"ById"))

##设置回调
$!callback.setFileName($tool.append($serviceName,".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.$entityName;importcom.baomidou.mybatisplus.extension.plugins.pagination.Page;importcom.baomidou.mybatisplus.extension.service.IService;importjava.util.List;importjava.util.Map;

##使用宏定义实现类注释信息
#tableComment("服务接口层")publicinterface $!{serviceName}extendsIService<$entityName>{/**
     * 查询${tableInfo.comment}分页列表
     * @param current 当前页码
     * @param size 每页页数
     * @param params 筛选条件
     * @return 分页列表
     */Page<$entityName> $queryPage(long current,long size,Map<String,Object> params);/**
     * 查询${tableInfo.comment}列表
     * @param params 筛选条件
     * @return 列表
     */List<$entityName> $queryList(Map<String,Object> params);/**
     * 通过主键查询${tableInfo.comment}详情
     * @param id 主键
     * @return ${tableInfo.comment}
     */
    $entityName $queryById($!pk.shortType $!pk.name);/**
     * 保存${tableInfo.comment}
     * @param $!{tool.firstLowerCase($entityName)} 筛选条件
     * @return 成功标志位
     */Boolean $save($entityName $!{tool.firstLowerCase($entityName)});/**
     * 更新${tableInfo.comment}
     * @param $!{tool.firstLowerCase($entityName)} 筛选条件
     * @return 成功标志位
     */Boolean $update($entityName $!{tool.firstLowerCase($entityName)});/**
     * 删除${tableInfo.comment}
     * @param id 主键id
     * @return 成功标志位
     */Boolean $delete($!pk.shortType $!pk.name);}
2.6、Template代码模板:serviceImpl.java.vm
##引入宏定义
$!{define.vm}
$!{init.vm}

##定义初始变量
#set($serviceImplName = $tool.append($tableInfo.name,"ServiceImpl"))
##实体类名
#set($entityName = $tool.append($tableInfo.name,"Entity"))
#set($serviceName = $tool.append($tableInfo.name,"Service"))
#set($daoName = $tool.append($tableInfo.name,"Dao"))
#set($queryPage = $tool.append("query", $tableInfo.name,"Page"))
#set($queryList = $tool.append("query", $tableInfo.name,"List"))
#set($queryById = $tool.append("query", $tableInfo.name,"ById"))
#set($save = $tool.append("save", $tableInfo.name))
#set($update = $tool.append("update", $tableInfo.name))
#set($delete = $tool.append("delete", $tableInfo.name,"ById"))

##设置回调
$!callback.setFileName($tool.append($serviceImplName,".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.$entityName;import $!{tableInfo.savePackageName}.dao.$daoName;import $!{tableInfo.savePackageName}.service.$serviceName;importorg.springframework.stereotype.Service;importcn.hutool.core.util.ObjectUtil;importcom.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;importcom.baomidou.mybatisplus.extension.plugins.pagination.Page;importcom.baomidou.mybatisplus.extension.service.impl.ServiceImpl;importorg.springframework.transaction.annotation.Transactional;importjavax.annotation.Resource;importjava.util.List;importjava.util.Map;

##使用宏定义实现类注释信息
#tableComment("服务层")@Service("$!tool.firstLowerCase($!{tableInfo.name})Service")publicclass $!{serviceImplName}extendsServiceImpl<$daoName, $entityName>implements $!{tableInfo.name}Service{@Resourceprivate $daoName $!tool.firstLowerCase($daoName);/**
     * 查询${tableInfo.comment}分页列表
     * @param current 当前页码
     * @param size 每页页数
     * @param params 筛选条件
     * @return 分页列表
     */@OverridepublicPage<$entityName> $queryPage(long current,long size,Map<String,Object> params){try{LambdaQueryWrapper<$entityName> wrapper =queryParams(params);Page<$entityName> page =newPage<>(current, size);this.$!{tool.firstLowerCase($daoName)}.selectPage(page, wrapper);return page;}catch(Exception e){throw e;}}/**
     * 查询${tableInfo.comment}列表
     * @param params 筛选条件
     * @return 列表
     */@OverridepublicList<$entityName> $queryList(Map<String,Object> params){try{LambdaQueryWrapper<$entityName> wrapper =queryParams(params);List<$entityName> list =this.$!{tool.firstLowerCase($daoName)}.selectList(wrapper);return list;}catch(Exception e){throw e;}}/**
     * 通过主键查询${tableInfo.comment}详情
     * @param id 主键
     * @return ${tableInfo.comment}
     */@Overridepublic $entityName $queryById($!pk.shortType $!pk.name){try{
            $entityName $!{tool.firstLowerCase($entityName)}=this.$!{tool.firstLowerCase($daoName)}.selectById($!pk.name);return $!{tool.firstLowerCase($entityName)};}catch(Exception e){throw e;}}/**
     * 保存${tableInfo.comment}
     * @param $!{tool.firstLowerCase($entityName)} 筛选条件
     * @return 成功标志位
     */@Override@Transactional(rollbackFor =Exception.class)publicBoolean $save($entityName $!{tool.firstLowerCase($entityName)}){try{int insert =this.$!{tool.firstLowerCase($daoName)}.insert($!{tool.firstLowerCase($entityName)});return insert >0;}catch(Exception e){throw e;}}/**
     * 更新${tableInfo.comment}
     * @param $!{tool.firstLowerCase($entityName)} 筛选条件
     * @return 成功标志位
     */@Override@Transactional(rollbackFor =Exception.class)publicBoolean $update($entityName $!{tool.firstLowerCase($entityName)}){try{int update =this.$!{tool.firstLowerCase($daoName)}.updateById($!{tool.firstLowerCase($entityName)});return update >0;}catch(Exception e){throw e;}}/**
     * 删除${tableInfo.comment}
     * @param id 主键id
     * @return 成功标志位
     */@Override@Transactional(rollbackFor =Exception.class)publicBoolean $delete($!pk.shortType $!pk.name){try{int delete =this.$!{tool.firstLowerCase($daoName)}.deleteById($!pk.name);return delete >0;}catch(Exception e){throw e;}}publicLambdaQueryWrapper<$entityName>queryParams(Map<String,Object> params){LambdaQueryWrapper<$entityName> wrapper =newLambdaQueryWrapper<>();// 筛选条件
        wrapper
#foreach($column in $tableInfo.fullColumn)
#if($!pk.name == $column.name || $tool.newHashSet("java.lang.Integer","int","java.lang.Short","short").contains($column.type)|| $tool.newHashSet("java.lang.Boolean","boolean").contains($column.type)|| $tool.newHashSet("java.lang.Long","long").contains($column.type)|| $tool.newHashSet("java.lang.Float","float","java.lang.Double","double").contains($column.type)).eq(ObjectUtil.isNotNull(params.get("$column.name")), $entityName::get$!{tool.firstUpperCase($column.name)}, params.get("$column.name"))
#elseif($tool.newHashSet("java.lang.String").contains($column.type)|| $tool.newHashSet("java.lang.Byte","byte").contains($column.type)).like(ObjectUtil.isNotNull(params.get("$column.name")), $entityName::get$!{tool.firstUpperCase($column.name)}, params.get("$column.name"))
#end
#end
            .eq(ObjectUtil.isNotNull(params.get("createId")), $entityName::getCreateId, params.get("createId")).eq(ObjectUtil.isNotNull(params.get("updateId")), $entityName::getUpdateId, params.get("updateId")).ge(ObjectUtil.isNotNull(params.get("createBeginTime")), $entityName::getCreateTime, params.get("createBeginTime")).le(ObjectUtil.isNotNull(params.get("createEndTime")), $entityName::getCreateTime, params.get("createEndTime")).ge(ObjectUtil.isNotNull(params.get("updateBeginTime")), $entityName::getUpdateTime, params.get("updateBeginTime")).le(ObjectUtil.isNotNull(params.get("updateEndTime")), $entityName::getUpdateTime, params.get("updateEndTime")).like(ObjectUtil.isNotNull(params.get("remark")), $entityName::getRemark, params.get("remark")).orderByDesc($entityName::getUpdateTime);return wrapper;}}

3、Column Config配置

Column Config配置

4、Global Config配置

4.1、Global Config配置:autoImport.vm
##自动导入包(仅导入实体属性需要的包,通常用于实体类)
#foreach($importin $importList)import $!import;
#end
4.2、Global Config配置:define.vm
##(Velocity宏定义)

##定义设置表名后缀的宏定义,调用方式:#setTableSuffix("Test")
#macro(setTableSuffix $suffix)
    #set($tableName = $!tool.append($tableInfo.name, $suffix))
#end

##定义设置包名后缀的宏定义,调用方式:#setPackageSuffix("Test")
#macro(setPackageSuffix $suffix)
#if($suffix!="")package #end#if($tableInfo.savePackageName!="")$!{tableInfo.savePackageName}.#{end}$!suffix;
#end

##定义直接保存路径与文件名简化的宏定义,调用方式:#save("/entity",".java")
#macro(save $path $fileName)
    $!callback.setSavePath($tool.append($tableInfo.savePath, $path))
    $!callback.setFileName($tool.append($tableInfo.name, $fileName))
#end

##定义表注释的宏定义,调用方式:#tableComment("注释信息")
#macro(tableComment $desc)/**
 * $!{tableInfo.comment}--$desc
 * @Author: ClancyLv
 * @Date: $!time.currTime()
 * @Description: $!{tableInfo.comment}
 */
#end

##定义GET,SET方法的宏定义,调用方式:#getSetMethod($column)
#macro(getSetMethod $column)public $!{tool.getClsNameByFullName($column.type)} get$!{tool.firstUpperCase($column.name)}(){return $!{column.name};}publicvoid set$!{tool.firstUpperCase($column.name)}($!{tool.getClsNameByFullName($column.type)} $!{column.name}){this.$!{column.name}= $!{column.name};}
#end
4.3、Global Config配置:init.vm
##初始化区域

##去掉表的t_前缀
$!tableInfo.setName($tool.getClassName($tableInfo.obj.name.replaceFirst("book_","")))

##参考阿里巴巴开发手册,POJO 类中布尔类型的变量,都不要加 is 前缀,否则部分框架解析会引起序列化错误
#foreach($column in $tableInfo.fullColumn)
#if($column.name.startsWith("is")&& $column.type.equals("java.lang.Boolean"))
    $!column.setName($tool.firstLowerCase($column.name.substring(2)))
#end
#end

##实现动态排除列,这里排除了通用类BaseEntity中的字段
#set($temp = $tool.newHashSet("delFlg","createId","updateId","createTime","updateTime","remark"))
#foreach($item in $temp)
    #set($newList = $tool.newArrayList())
    #foreach($column in $tableInfo.fullColumn)
        #if($column.name!=$item)
            ##带有反回值的方法调用时使用$tool.call来消除返回值
            $tool.call($newList.add($column))
        #end
    #end
    ##重新保存
    $tableInfo.setFullColumn($newList)
#end

##对importList进行篡改
#set($temp = $tool.newHashSet())
#foreach($column in $tableInfo.fullColumn)
    #if(!$column.type.startsWith("java.lang."))
        ##带有反回值的方法调用时使用$tool.call来消除返回值
        $tool.call($temp.add($column.type))
    #end
#end
##覆盖
#set($importList = $temp)
4.4、Global Config配置:mybatisSupport.vm
##针对Mybatis 进行支持,主要用于生成xml文件
#foreach($column in $tableInfo.fullColumn)
    ##储存列类型
    $tool.call($column.ext.put("sqlType", $tool.getField($column.obj.dataType,"typeName")))
    #if($tool.newHashSet("java.lang.String").contains($column.type))
        #set($jdbcType="VARCHAR")
    #elseif($tool.newHashSet("java.lang.Boolean","boolean").contains($column.type))
        #set($jdbcType="BOOLEAN")
    #elseif($tool.newHashSet("java.lang.Byte","byte").contains($column.type))
        #set($jdbcType="BYTE")
    #elseif($tool.newHashSet("java.lang.Integer","int","java.lang.Short","short").contains($column.type))
        #set($jdbcType="INTEGER")
    #elseif($tool.newHashSet("java.lang.Long","long").contains($column.type))
        #set($jdbcType="INTEGER")
    #elseif($tool.newHashSet("java.lang.Float","float","java.lang.Double","double").contains($column.type))
        #set($jdbcType="NUMERIC")
    #elseif($tool.newHashSet("java.util.Date","java.sql.Timestamp","java.time.Instant","java.time.LocalDateTime","java.time.OffsetDateTime","    java.time.ZonedDateTime").contains($column.type))
        #set($jdbcType="TIMESTAMP")
    #elseif($tool.newHashSet("java.sql.Date","java.time.LocalDate").contains($column.type))
        #set($jdbcType="TIMESTAMP")
    #else
        ##其他类型
        #set($jdbcType="VARCHAR")
    #end
    $tool.call($column.ext.put("jdbcType", $jdbcType))
#end

##定义宏,查询所有列
#macro(allSqlColumn)#foreach($column in $tableInfo.fullColumn)$column.obj.name#if($velocityHasNext), #end#end#end

三、 使用

1、连接数据库

连接数据库

2、选择

选择

3、配置

补充包基础路径(不用到具体dao或entity或…层)
选择组名,与配置模板选定的组名一致
选择要生成代码的模板
点击OK
配置

标签: intellij-idea java ide

本文转载自: https://blog.csdn.net/ClancyLv/article/details/131928746
版权归原作者 ClancyLv 所有, 如有侵权,请联系我们删除。

“工具—IDEA代码自动生成插件EasyCode”的评论:

还没有评论