Mybatis-plus代码生成器 自动生成增删改查代码

第一步 安装依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.7</version>
</dependency>
<dependency>
	<groupId>org.apache.velocity</groupId>
	<artifactId>velocity</artifactId>
	<version>1.7</version>
</dependency>

第二步 编写启动文件

public class CodeGenerator {
    public static void main(String[] args) {
        generate();
    }
    private static void generate(){
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/springboot?serverTimezone=GMT%2b8", "root", "password")
                .globalConfig(builder -> builder
                        .author("quan")	//设置注释-作者
                        .outputDir(Paths.get(System.getProperty("user.dir")) + "\\src\\main\\java\\")	//设置文件输出路径
                        .commentDate("yyyy-MM-dd")	//设置注释-编写日期
                )
                .packageConfig(builder -> builder
                        .parent("com.example.springboot_vue")	//设置包名
                        .moduleName(null)	//设置模板名
                        .pathInfo(Collections.singletonMap(OutputFile.xml, "D:\\vueProjectSystem\\springboot_vue\\src\\main\\resources\\mapper\\"))	//设置mapperXml生成路径
                )
                .strategyConfig(builder ->{
                            builder.mapperBuilder().enableFileOverride();	//设置mapper文件覆盖
                            builder.serviceBuilder().enableFileOverride();	//设置service文件覆盖
                            builder.controllerBuilder().enableFileOverride();	//设置controller文件覆盖
                            builder.entityBuilder().enableFileOverride().enableLombok();	//设置entity文件覆盖和entity文件使用lombok注解简化代码
                            builder.mapperBuilder().enableMapperAnnotation().build();	//开启生成@mapper
                      		builder.controllerBuilder().enableHyphenStyle()	// 开启驼峰转连字符
                                    .enableRestStyle();  // 开启生成@RestController 控制器
                            builder.addInclude("sys_user") // 设置需要生成的表名
                                    .addTablePrefix("t_", "c_","sys");// 设置过滤表前缀
                        }

                )
                .execute();
    }
}

第三步 编写controller模板,自动生成controller代码(文件名为controller.java.vm)

package ${package.Controller};

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${package.Entity}.ErrorCode;
import ${package.Entity}.Pages;
import ${package.Entity}.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import $!{package.Service}.$!{table.serviceName};
import ${package.Entity}.${entity};

#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end

/**
 * <p>
 * $!{table.comment} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end

#else
    #if(${superControllerClass})
    public class ${table.controllerName} extends ${superControllerClass} {
    #else
    public class ${table.controllerName} {
    #end

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

@GetMapping("/search")
public Result search(@RequestParam Integer currentPage,@RequestParam Integer pageSize,@RequestParam String username,@RequestParam String email,@RequestParam String address){
    QueryWrapper<${entity}> queryWrapper=new QueryWrapper<>();
    if(!username.isBlank()){
        queryWrapper.like("username",username);
    }
    if(!email.isBlank()){
        queryWrapper.like("email",email);
    }
    if(!address.isBlank()){
        queryWrapper.like("address",address);
    }
    IPage<${entity}> page = new Page<>(currentPage, pageSize);
    IPage<${entity}> ${table.entityPath}Page=${table.entityPath}Service.page(page,queryWrapper);
    List<${entity}> ${table.entityPath}List = ${table.entityPath}Page.getRecords();
    long total = ${table.entityPath}Page.getTotal();
    Pages pages=new Pages(total,${table.entityPath}List);
    return Result.success(pages);
}

@PostMapping("/saveOrUpdate")
public Result saveOrUpdate(@RequestBody ${entity} ${table.entityPath}){
    Boolean code=${table.entityPath}Service.saveOrUpdate(${table.entityPath});
    if(code==true){
        return Result.success();
    }else{
        return Result.error(ErrorCode.INSERT_ERROR.getCode(), ErrorCode.INSERT_ERROR.getMsg());
    }
}

@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id){
    QueryWrapper<${entity}> queryWrapper=new QueryWrapper<>();
    queryWrapper.eq("id",id);
    Boolean code=${table.entityPath}Service.remove(queryWrapper);
    if(code==true){
        return Result.success();
    }else{
        return Result.error(ErrorCode.REMOVE_ERROR.getCode(), ErrorCode.REMOVE_ERROR.getMsg());
    }
}

@DeleteMapping("/ids/{ids}")
public Result deleteByIds(@PathVariable Integer[] ids){
    List<Integer> list=new ArrayList<>();
    for(Integer id:ids){
        list.add(id);
    }
    Boolean code=${table.entityPath}Service.removeBatchByIds(list);
    if(code==true){
        return Result.success();
    }else{
        return Result.error(ErrorCode.PATCH_REMOVE_ERROR.getCode(), ErrorCode.PATCH_REMOVE_ERROR.getMsg());
    }
}

}

#end


附:

1.Result类

package com.example.springboot_vue.entity;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class Result {
    private int code;
    private String msg;
    private Object data;

    public static Result success(){
        return new Result(200,"success",null);
    }
    public static Result success(Object data){
        return new Result(200,"success",data);
    }
    public static Result error(int code,String msg){
        return new Result(code,msg,null);
    }
}

2.ErrorCode类

package com.example.springboot_vue.entity;

import lombok.AllArgsConstructor;

@AllArgsConstructor
public enum ErrorCode {
    SYSTEM_ERROR(1001,"系统错误"),
    INSERT_ERROR(1002,"插入失败"),
    REMOVE_ERROR(1003,"删除失败"),
    PATCH_REMOVE_ERROR(1004,"批量删除失败");
    private int code;
    private String msg;
    public int getCode(){
        return this.code;
    }

    public void setCode(int code){
        this.code=code;
    }

    public String getMsg(){
        return this.msg;
    }

    public void setMsg(String msg){
        this.msg=msg;
    }
}

3.Pages类

package com.example.springboot_vue.entity;

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

import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Pages<T> {
    private long total;
    private List<T> data;
}

MyBatis-Plus代码生成器AutoGenerator可以帮助我们快速生成Controller、Service、Mapper、Entity等各个模块的代码,提高了开发效率。我们只需要准备好相关的配置,例如数据库连接信息和表名,AutoGenerator就可以自动生成相应的代码。 通过使用MyBatis-Plus代码生成器,我们可以轻松搭建一个高效的代码自动生成器。在Service层中,我们可以使用生成的代码进行CRUD操作,这大大减少了我们手动编写基础的增删改查代码的工作量。 代码自动生成器的使用非常方便,只需提供数据库的表名作为输入,生成器就会自动帮我们创建各种代码。这个过程非常简洁和清爽,对于开发人员来说是一个很大的福利,能够节省大量的时间和精力。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [必须了解的三种 mybatis-plus自动生成代码](https://blog.csdn.net/SoulNone/article/details/126445011)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [MyBatis-Plus——代码自动生成器](https://blog.csdn.net/m0_67402235/article/details/126035075)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值