IDEA integrates the EasyCode plug-in to quickly generate custom mybatisplus code

1. idea integrates easyCode plug-in

In the idea plug-in, search for the EasyCode plug-in, download and install it. 

2. Introduction to easyCode plug-in

The easyCode plug-in can modify the author's name, that is, after the code is generated, the name of the corresponding author is automatically added to the comments. 

2.1 Type Mapper

Type Mapper refers to the type conversion between the fields in the database in the mapper.xml file and the fields in the code in Java, as well as the generation of mybatis data. The most common form is as follows, that is, the conversion between property property in Java and column name column data type in the database jdbcType.

<resultMap type="com.school.infomation.entity.SysRoleEntity" id="SysRoleMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="code" column="code" jdbcType="VARCHAR"/>
        <result property="isEnabled" column="is_enabled" jdbcType="INTEGER"/>
        <result property="isDeleted" column="is_deleted" jdbcType="INTEGER"/>
        <result property="remark" column="remark" jdbcType="VARCHAR"/>
        <result property="createUser" column="create_user" jdbcType="INTEGER"/>
        <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
        <result property="updateUser" column="update_user" jdbcType="INTEGER"/>
        <result property="updateTime" column="update_time" jdbcType="TIMESTAMP"/>
    </resultMap>

2.2 Template

Template is the core content and can generate corresponding code. At the same time, you can select the corresponding plug-in. The default form is mybatis. If you use mybatisPlus, you can choose MybatisPlus to automatically generate the corresponding code.

 2.3 Column Config

Column Config is mainly used to perform additional configuration related to columns and is basically not used. Just default.

2.4 Global Config

Global Config global configuration, mainly configures the import of related packages, code annotations and related generation.

2.5 Custom configuration mybatisplus

First, let's look at an entity class. From this entity class, we can find that this class inherits BaseEntity.

SysRoleEntity entity class

package com.school.infomation.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.school.infomation.core.security.entity.BaseEntity;
import com.school.infomation.enums.status.EnabledEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@TableName("sys_role")
public class SysRoleEntity extends BaseEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 角色名称
     */
    private String name;

    /**
     * 角色编码
     */
    private String code;

    /**
     * 是否启用 0启用 1禁用
     */
    private EnabledEnum isEnabled;

    /**
     * 备注
     */
    private String remark;
}

BaseEntity entity class

package com.school.infomation.core.security.entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.baomidou.mybatisplus.annotation.*;
import com.school.infomation.enums.status.DeletedEnum;
import com.school.infomation.utils.DateUtil;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 基础实体类
 */
@Data
public class BaseEntity implements Serializable {
    /**
     * 主键id
     */
    @JSONField(serializeUsing = ToStringSerializer.class)
    @TableId(value = "id", type = IdType.ASSIGN_ID)
    private Long id;

    /**
     * 创建人
     */
    @TableField(fill = FieldFill.INSERT)
    @JSONField(serializeUsing = ToStringSerializer.class)
    private Long createUser;

    /**
     * 创建时间
     */
    @TableField(fill = FieldFill.INSERT)
    @DateTimeFormat(pattern = DateUtil.PATTERN_DATETIME)
    @JSONField(format = DateUtil.PATTERN_DATETIME)
    private LocalDateTime createTime;

    /**
     * 更新人
     */
    @TableField(fill = FieldFill.INSERT_UPDATE)
    @JSONField(serializeUsing = ToStringSerializer.class)
    private Long updateUser;

    /**
     * 更新时间
     */
    @TableField(fill = FieldFill.INSERT_UPDATE)
    @DateTimeFormat(pattern = DateUtil.PATTERN_DATETIME)
    @JSONField(format = DateUtil.PATTERN_DATETIME)
    private LocalDateTime updateTime;

    /**
     * 状态[0:未删除,1:删除]
     */
    @TableLogic
    @TableField(fill = FieldFill.INSERT)
    private DeletedEnum isDeleted;
}

If you use the default configuration of easyCode, the com.school.infomation.core.security.entity.BaseEntity package cannot be automatically imported when generating entity classes. At this time, you need to add a global configuration

Another problem is that if you choose to inherit BaseEntity, it means that the generated SysRole entity class cannot have public fields such as id and createUser. This needs to be eliminated.

#set($temp = $tool.newHashSet("id", "createUser", "updateUser", "createTime", "updateTime", "isDeleted"))
#foreach($item in $temp)
    #set($newList = $tool.newArrayList())
    #foreach($column in $tableInfo.fullColumn)
        #if($column.name!=$item)
            $tool.call($newList.add($column))
        #end
    #end
    $tableInfo.setFullColumn($newList)
#end

The files that generate entity classes are followed by the Entity suffix. Therefore, you need to modify the entity.java.vm file in the Template.

It is recommended that when modifying these files, we can customize a group, copy other group files, and then modify them. 

We can also add a lombok plug-in to delete the automatically generated set and get methods.

The specific modified files are as follows:

entity.java.vm file

##导入宏定义
$!{define.vm}
##保存文件(宏定义)
#save("/entity", "Entity.java")
#set($temp = $tool.newHashSet("id", "createUser", "updateUser", "createTime", "updateTime", "isDeleted"))
#foreach($item in $temp)
    #set($newList = $tool.newArrayList())
    #foreach($column in $tableInfo.fullColumn)
        #if($column.name!=$item)
            $tool.call($newList.add($column))
        #end
    #end
    $tableInfo.setFullColumn($newList)
#end

#setPackageSuffix("entity")
##自动导入包(全局变量)
$!{customExtendBaseEntity.vm}
$!{autoImport.vm}
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

##表注释(宏定义)
#tableComment("表实体类")
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("$!{tableInfo.obj.name}")
public class $!{tableInfo.name}Entity extends BaseEntity implements Serializable {

    private static final long serialVersionUID = 1L;

#foreach($column in $tableInfo.fullColumn)
    #if(${column.comment})//${column.comment}#end
    
    private $!{tool.getClsNameByFullName($column.type)} $!{column.name};
#end

}

Because easycode automatically generates dao files, it can also be modified into mapper files.

mapper.java.vm file

##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("Mapper")

##保存文件(宏定义)
#save("/mapper", "Mapper.java")

##包路径(宏定义)
#setPackageSuffix("mapper")

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name}Entity;

##表注释(宏定义)
#tableComment("表数据库访问层")
@Mapper
public interface $!{tableName} extends BaseMapper<$!{tableInfo.name}Entity> {

}

mapper.xml.vm file

##引入mybatis支持
$!{mybatisSupport.vm}

##设置保存名称与保存位置
$!callback.setFileName($tool.append($!{tableInfo.name}, "Mapper.xml"))
$!callback.setSavePath($tool.append($modulePath, "/src/main/resources/mapper"))

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

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

    <resultMap type="$!{tableInfo.savePackageName}.entity.$!{tableInfo.name}Entity" id="$!{tableInfo.name}Map">
#foreach($column in $tableInfo.fullColumn)
        <result property="$!column.name" column="$!column.obj.name" jdbcType="$!column.ext.jdbcType"/>
#end
    </resultMap>

</mapper>

service.java.xml file

##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("Service")

##保存文件(宏定义)
#save("/service", "Service.java")

##包路径(宏定义)
#setPackageSuffix("service")

import com.baomidou.mybatisplus.extension.service.IService;
import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name}Entity;

##表注释(宏定义)
#tableComment("表服务接口")
public interface $!{tableName} extends IService<$!{tableInfo.name}Entity>{

}

serviceImpl.java.vm file

##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("ServiceImpl")

##保存文件(宏定义)
#save("/service/impl", "ServiceImpl.java")

##包路径(宏定义)
#setPackageSuffix("service.impl")

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import $!{tableInfo.savePackageName}.mapper.$!{tableInfo.name}Mapper;
import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name}Entity;
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.stereotype.Service;

##表注释(宏定义)
#tableComment("表服务实现类")
@Service
public class $!{tableName} extends ServiceImpl<$!{tableInfo.name}Mapper, $!{tableInfo.name}Entity> implements $!{tableInfo.name}Service{

}

controller.java.vm file

This file can customize the returned tool class. If you customize the returned class ResultUtil.java; when importing a custom package, you need to configure the relevant package name globally and then import it.

$!{resultUtil.vm}

##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("Controller")
##保存文件(宏定义)
#save("/controller", "Controller.java")
##包路径(宏定义)
#setPackageSuffix("controller")

##定义服务名
#set($serviceName = $!tool.append($!tool.firstLowerCase($!tableInfo.name), "Service"))
##定义实体对象名
#set($entityName = $!tool.firstLowerCase($!tableInfo.name))
$!{resultUtil.vm}
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name}Entity;
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

##表注释(宏定义)
#tableComment("表控制层")
@RestController
@RequestMapping("$!tool.firstLowerCase($!tableInfo.name)")
public class $!{tableName} {
    /**
     * 服务对象
     */
    @Resource
    private $!{tableInfo.name}Service $!{serviceName};

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param $!entityName 查询实体
     * @return 所有数据
     */
    @GetMapping
    public ResultUtil selectAll(Page<$!{tableInfo.name}Entity> page, $!{tableInfo.name}Entity $!entityName) {
        return ResultUtil.success(this.$!{serviceName}.page(page, new QueryWrapper<>($!entityName)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResultUtil selectOne(@PathVariable Serializable id) {
        return ResultUtil.success(this.$!{serviceName}.getById(id));
    }

    /**
     * 新增数据
     *
     * @param $!entityName 实体对象
     * @return 新增结果
     */
    @PostMapping
    public ResultUtil insert(@RequestBody $!{tableInfo.name}Entity $!entityName) {
        return ResultUtil.success(this.$!{serviceName}.save($!entityName));
    }

    /**
     * 修改数据
     *
     * @param $!entityName 实体对象
     * @return 修改结果
     */
    @PutMapping
    public ResultUtil update(@RequestBody $!{tableInfo.name}Entity $!entityName) {
        return ResultUtil.success(this.$!{serviceName}.updateById($!entityName));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public ResultUtil delete(@RequestParam("idList") List<Long> idList) {
        return ResultUtil.success(this.$!{serviceName}.removeByIds(idList));
    }
}

3. Generate code

3.1 Link to the database in idea

 Just enter your database account password and database name.

 3.2 Select the corresponding table to generate code

 Select the package path, the path to save after code generation, and select custom grouping rules for code generation.

 The generated code structure is as follows:

Guess you like

Origin blog.csdn.net/yu1431/article/details/130924049