EasyCode全自动单表增删改查!

easycode,全自动,删改 · 浏览次数 : 96

小编点评

**代码描述** 该代码实现了一个统一认证中心用户单(AuthLoginUser)表控制层,包含以下主要功能: 1. **分页查询数据**:通过 `BaseLimitRequest` 实体进行分页查询,并封装结果集。 2. **通过主键查询单条数据**:通过 `id` 的参数,直接查询数据库获取单条数据。 3. **新增数据**:通过 `AuthLoginUser` 实体创建新数据并保存到数据库。 4. **修改数据**:通过 `AuthLoginUser` 实体更新已有数据并保存。 5. **删除数据**:通过 `idList` 的参数删除多个数据并返回删除结果。 **主要类** * `AuthLoginUserController`:控制器的实现类,包含 `selectAll`, `selectOne`, `insert`, `update` 和 `delete` 方法。 * `AuthLoginUserService`:与数据库进行交互的业务逻辑实现类。 **注解** * `@Resource` 注解用于注入 `AuthLoginUserService`。 * `@RequestMapping` 注解用于定义 API 路径。 * `@PostMapping`, `@PutMapping` 和 `@DeleteMapping` 注解用于处理 POST、PUT 和 DELETE 请求。 * `@RequestParam` 注解用于从请求中获取参数。 * `@RequestBody` 注解用于将请求体数据解析为实体对象。 **效果** 通过使用以上代码,您可以构建一个完整的统一认证中心用户单控制层,方便管理用户数据。

正文

需要IDEA下载EasyCode插件

image

准备好三个基础Base类

分页封装基础

package com.gton.io;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @description: 分页参数对象
 * 贫血型模型
 * @author: GuoTong
 * @createTime: 2022-09-24 13:31
 * @since JDK 1.8 OR 11
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BasePage implements Serializable {

    /**
     * Description:  当前页 || 默认是从第一页开始
     *
     * @author: GuoTong
     * @date: 2022-09-24 13:32:36
     */
    private long pageIndex = 1;


    /**
     * Description:  每页显示条数 || 默认是每页展示10条
     *
     * @author: GuoTong
     * @date: 2022-09-24 13:32:36
     */
    private long pageSize = 10;


    public long getPageIndex() {
        if (this.pageIndex <= 1) {
            this.pageIndex = 1;
        }
        return pageIndex;
    }

    public long getPageSize() {
        if (this.pageSize <= 1) {
            this.pageSize = 10;
        }
        return pageSize;
    }


}

分页请求对象

package com.gton.io;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * @description: 通用请求
 * @author: GuoTong
 * @createTime: 2022-12-02 14:09
 * @since JDK 1.8 OR 11
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BaseLimitRequest<T> extends BasePage {

    /**
     * Description: 实体类
     */
    private T requestBody;


    /**
     * Description: 开始时间
     */
    private LocalDateTime beginTime;


    /**
     * Description: 结束时间
     */
    private LocalDateTime endTime;

}

基本通用响应对象

package com.gton.io;

import com.gton.util.ContextCommonMsg;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * @description: 通用返回对象
 * 贫血型模型
 * @author: GuoTong
 * @createTime: 2022-09-24 13:16
 * @since JDK 1.8 OR 11
 **/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Resp<T> implements Serializable {
    //状态码
    private String code;

    //提示信息
    private String msg;

    //返回的数据
    private T data;


    /**
     * Description:常用返回数据抽离
     */
    public static <T> Resp<T> LoginOk() {
        return new Resp<T>().
                setCode(ContextCommonMsg.LOGIN_SUCCESS_CODE).
                setMsg(ContextCommonMsg.LOGIN_SUCCESS_MSG);
    }

    public static <T> Resp<T> LoginFail() {
        return new Resp<T>().
                setCode(ContextCommonMsg.LOGIN_FAIL_CODE).
                setMsg(ContextCommonMsg.LOGIN_FAIL_MSG);
    }

    public static <T> Resp<T> error(String errorMsg) {
        return new Resp<T>().
                setCode(ContextCommonMsg.FAIL_CODE).
                setMsg(errorMsg);
    }

    public static <T> Resp<T> error() {
        return new Resp<T>().
                setCode(ContextCommonMsg.FAIL_CODE).
                setMsg(ContextCommonMsg.FAIL_MSG);
    }

    public static <T> Resp<T> error(String errorMsg, String failCode) {
        return new Resp<T>().
                setCode(failCode).
                setMsg(errorMsg);
    }

    public static <T> Resp<T> error(String errorMsg, String failCode, T data) {
        return new Resp<T>().
                setCode(failCode).
                setData(data).
                setMsg(errorMsg);
    }

    public static <T> Resp<T> Ok(T data) {
        return new Resp<T>().
                setCode(ContextCommonMsg.SUCCESS_CODE).
                setMsg(ContextCommonMsg.SUCCESS_MSG).
                setData(data);
    }

    public static <T> Resp<T> Ok() {
        return new Resp<T>().
                setCode(ContextCommonMsg.SUCCESS_CODE).
                setMsg(ContextCommonMsg.SUCCESS_MSG);
    }

    public static <T> Resp<T> Ok(T data, String msg) {
        return new Resp<T>().
                setCode(ContextCommonMsg.SUCCESS_CODE).
                setMsg(msg).
                setData(data);
    }

    public static <T> Resp<T> Ok(T data, String msg, String successCode) {
        return new Resp<T>().
                setCode(successCode).
                setMsg(msg).
                setData(data);
    }

}

分页查询通用响应

package com.gton.io;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * @description: 通用响应
 * @author: GuoTong
 * @createTime: 2022-12-02 14:12
 * @since JDK 1.8 OR 11
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BaseLimitResponse<T> extends BasePage {

    /**
     * Description: 当前页数据
     */
    private List<T> responseBody;

    /**
     * Description:  总条数
     */
    private long totalNum;


    /**
     * Description:  总页数
     */
    private long pageCount;


    public static <T> BaseLimitResponse<T> getInstance() {
        return new BaseLimitResponse<>();
    }

    /**
     * Description: 获取响应对象
     *
     * @param responseBody 当前页数据
     * @param totalNum     总数据
     * @param pageCount    总页数
     * @param pageIndex    当前页
     * @param pageSize     每页展示数据大小
     * @author: GuoTong
     * @date: 2022-12-02 15:01:48
     * @return:com.gton.io.BaseLimitResponse<T>
     */
    public static <T> BaseLimitResponse<T> getInstance(List<T> responseBody, long totalNum, long pageCount, long pageIndex, long pageSize) {
        BaseLimitResponse<T> response = new BaseLimitResponse<>();
        response.setResponseBody(responseBody);
        response.setPageCount(pageCount);
        response.setTotalNum(totalNum);
        response.setPageSize(pageSize);
        response.setPageIndex(pageIndex);
        return response;
    }
}

模板

controller.java.vmCopy

##导入宏定义
$!{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))

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gton.io.BaseLimitRequest;
import com.gton.io.BaseLimitResponse;
import com.gton.io.Resp;
import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.web.bind.annotation.*;
import com.gton.annotation.SwaggerScanClass;
import java.io.Serializable;
import java.util.List;

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

   /**
     * 分页查询数据
     *
     * @param limitRequest 查询实体
     * @return 所有数据
     */
    @PostMapping("/queryLimit")
     public Resp<BaseLimitResponse<$!tableInfo.name>> selectAll(@RequestBody BaseLimitRequest<$!tableInfo.name> limitRequest) {
        // 分页查询
        IPage<$!tableInfo.name> page = this.$!{serviceName}.queryLimitPage(limitRequest);
        // 封装返回结果集
        BaseLimitResponse<$!tableInfo.name> data = BaseLimitResponse.getInstance(page.getRecords(), page.getTotal(), page.getPages(), limitRequest.getPageIndex(), limitRequest.getPageSize());
        return Resp.Ok(data);
    }
   
   /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/queryOne/{id}")
    public Resp<$!tableInfo.name> selectOne(@PathVariable("id") Serializable id) {
         return Resp.Ok(this.$!{serviceName}.getById(id));
    }

   /**
     * 新增数据
     *
     * @param authLoginUser 实体对象
     * @return 新增结果
     */
    @PostMapping("/save")
    public Resp<String> insert(@RequestBody $!tableInfo.name $!entityName) {
        boolean save = false;
        String executeMsg = null;
        try {
            save = this.$!{serviceName}.save($!entityName);
            executeMsg = "新增成功,id 是:" + $!{entityName}.getId();
        } catch (Exception e) {
            executeMsg = e.getMessage();
        }
        return save ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
    }

    /**
     * 修改数据
     *
     * @param $!entityName 实体对象
     * @return 修改结果
     */
    @PutMapping("/update")
    public Resp<String> update(@RequestBody $!tableInfo.name $!entityName) {

        boolean update = false;
        String executeMsg = null;
        try {
            update = this.$!{serviceName}.updateById($!entityName);
            executeMsg = "修改成功,id 是:" + $!{entityName}.getId();
        } catch (Exception e) {
            executeMsg = e.getMessage();
        }
        return update ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping("/dels")
    public Resp<String> delete(@RequestParam("idList") List<Long> idList) {
        boolean delNumber = false;
        String executeMsg = null;
        try {
            delNumber = this.$!{serviceName}.removeByIds(idList);
            executeMsg = "删除成功,ids 是:" + idList;
        } catch (Exception e) {
            executeMsg = e.getMessage();
        }
        return delNumber ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
    }
}


dao.java.vmCopy

##导入宏定义
$!{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;

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

}

mapper.xml.vm

##引入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}" id="$!{tableInfo.name}Map">
#foreach($column in $tableInfo.fullColumn)
        <result property="$!column.name" column="$!column.obj.name" jdbcType="$!column.ext.jdbcType"/>
#end
    </resultMap>

</mapper>

entity.java.vmCopy

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

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

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

##自动导入包(全局变量)
$!{autoImport.vm}
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty;
import java.time.LocalDateTime;
import org.springframework.format.annotation.DateTimeFormat;

##表注释(宏定义)
#tableComment("表实体类")
@Getter
@Setter
@Accessors(chain = true)
@TableName("$!{tableInfo.name}")
@ApiModel(value = "$!{tableInfo.name}", description = "EasyCode")
public class $!{tableInfo.name} implements Serializable {
 private static final long serialVersionUID = 1L;
#foreach($column in $tableInfo.fullColumn)
   
    #if(${column.obj.name} == "id")
    @TableId(value = "id", type = IdType.ASSIGN_ID) 
    #elseif(${column.obj.name} == "create_time")
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    #elseif(${column.obj.name} == "update_time")
    @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
    #else
    @TableField(value = "${column.obj.name}")
    #end
    @ApiModelProperty("${column.comment}")
    #if($!{tool.getClsNameByFullName($column.type)} == "Date")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime $!{column.name};
    #else 
    private $!{tool.getClsNameByFullName($column.type)} $!{column.name};
    #end
#end

}

service.java.vm

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

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

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

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

import com.baomidou.mybatisplus.extension.service.IService;
import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gton.io.BaseLimitRequest;

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

/**
     * Description:  分页查询
     *
     * @param limitRequest 分页查询参数
     * @author: GuoTong
     * @date: 2022-12-02 14:57:06
     * @return:com.baomidou.mybatisplus.core.metadata.IPage
     */
    IPage<$!tableInfo.name> queryLimitPage(BaseLimitRequest<$!tableInfo.name> limitRequest);
}

serviceImpl.java.vm

##导入宏定义
$!{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};
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gton.io.BaseLimitRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;

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

    @Autowired
    private $!{tableInfo.name}Mapper $!tool.firstLowerCase($tableInfo.name)Mapper;
    
    
    /**
     * Description:  分页查询
     *
     * @param limitRequest 分页查询参数
     * @author: GuoTong
     * @date: 2022-12-02 14:57:06
     * @return:com.baomidou.mybatisplus.core.metadata.IPage
     */
    @Override
    public IPage<$!{tableInfo.name}> queryLimitPage(BaseLimitRequest<$!{tableInfo.name}> limitRequest) {
        $!{tableInfo.name} requestBody = limitRequest.getRequestBody();
        long pageIndex = limitRequest.getPageIndex();
        long pageSize = limitRequest.getPageSize();
        IPage<$!{tableInfo.name}> page = new Page<>(pageIndex, pageSize);
        QueryWrapper<$!{tableInfo.name}> queryWrapper = new QueryWrapper<>();
        byte[] bytes = JSON.toJSONBytes(requestBody);
        JSONObject thisObj = JSON.parseObject(bytes);
        Set<Map.Entry<String, Object>> entries = thisObj.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            String key = entry.getKey();
            StringBuilder column = new StringBuilder();
            char[] chars = key.toCharArray();
            for (char aChar : chars) {
                if (Character.isUpperCase(aChar)) {
                    column.append("_");
                }
                column.append(aChar);
            }
            queryWrapper.eq(getValueIsBoolean(entry.getValue()), column.toString(), entry.getValue());
        }
        LocalDateTime beginTime = limitRequest.getBeginTime();
        LocalDateTime endTime = limitRequest.getEndTime();
        queryWrapper.ge(getValueIsBoolean(beginTime), "create_time", beginTime);
        queryWrapper.le(getValueIsBoolean(endTime), "create_time", beginTime);
        return $!{tool.firstLowerCase($tableInfo.name)}Mapper.selectPage(page, queryWrapper);
    }
    
    
    private boolean getValueIsBoolean(Object object) {

        if (object instanceof String) {
            return StringUtils.isNotEmpty((CharSequence) object);
        }
        return !Objects.isNull(object);
    }
}

效果:

image

生成:
image

Controller查看

package com.gton.auth.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gton.auth.entity.AuthLoginUser;
import com.gton.auth.service.AuthLoginUserService;
import com.gton.io.BaseLimitRequest;
import com.gton.io.BaseLimitResponse;
import com.gton.io.Resp;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * 统一认证中心用户单(AuthLoginUser)表控制层
 *
 * @author 郭童
 * @since 2022-12-02 14:27:50
 */
@RestController
@RequestMapping("authLoginUser")
public class AuthLoginUserController {
    /**
     * 服务对象
     */
    @Resource
    private AuthLoginUserService authLoginUserService;

    /**
     * 分页查询数据
     *
     * @param limitRequest 查询实体
     * @return 所有数据
     */
    @PostMapping("/queryLimit")
    public Resp<BaseLimitResponse<AuthLoginUser>> selectAll(@RequestBody BaseLimitRequest<AuthLoginUser> limitRequest) {
        // 分页查询
        IPage<AuthLoginUser> page = this.authLoginUserService.queryLimitPage(limitRequest);
        // 封装返回结果集
        BaseLimitResponse<AuthLoginUser> data = BaseLimitResponse.getInstance(page.getRecords(), page.getTotal(), page.getPages(), limitRequest.getPageIndex(), limitRequest.getPageSize());
        return Resp.Ok(data);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/queryOne/{id}")
    public Resp<AuthLoginUser> selectOne(@PathVariable("id") Serializable id) {
        return Resp.Ok(this.authLoginUserService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param authLoginUser 实体对象
     * @return 新增结果
     */
    @PostMapping
    public Resp<String> insert(@RequestBody AuthLoginUser authLoginUser) {
        boolean save = false;
        String executeMsg = null;
        try {
            save = this.authLoginUserService.save(authLoginUser);
            executeMsg = "新增成功,id 是:" + authLoginUser.getId();
        } catch (Exception e) {
            executeMsg = e.getMessage();
        }
        return save ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
    }

    /**
     * 修改数据
     *
     * @param authLoginUser 实体对象
     * @return 修改结果
     */
    @PutMapping
    public Resp<String> update(@RequestBody AuthLoginUser authLoginUser) {

        boolean update = false;
        String executeMsg = null;
        try {
            update = this.authLoginUserService.updateById(authLoginUser);
            executeMsg = "修改成功,id 是:" + authLoginUser.getId();
        } catch (Exception e) {
            executeMsg = e.getMessage();
        }
        return update ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public Resp<String> delete(@RequestParam("idList") List<Long> idList) {
        boolean delNumber = false;
        String executeMsg = null;
        try {
            delNumber = this.authLoginUserService.removeByIds(idList);
            executeMsg = "删除成功,ids 是:" + idList;
        } catch (Exception e) {
            executeMsg = e.getMessage();
        }
        return delNumber ? Resp.Ok(executeMsg) : Resp.error(executeMsg);
    }
}


快拿去试一试吧

与EasyCode全自动单表增删改查!相似的内容: