EasyCode代码生成插件-模板分享(基于数据表生成MyBatisPlus格式的dao,service,controller和vue组件)

目录

概述

使用演示

模板代码 

  实体类pojo 

 表现层controller

业务层service接口

 业务层serviceImpl实现类

持久层dao

Vue组件 


 

概述

本片博客用于分享EasyCode的自定义模板(模板在篇末),用于简化开发,免去重复性的工作。

作用:

1.根据数据库表,后端生成基于MyBatisPlus结构下的实体类pojo,持久层dao,业务层service,表现层controller和前端vue实现增删改查功能的组件

2.表现层controller中生成基本增删改分页查询方法。

3.vue组件组件基于后端controller接口实现基本增删改查功能结构。

 

使用演示

操作前提: 

① 创建好一个springboot基本项目。

8aa319d84e5641748cd09fd04981da6c.png

 

 ② 导入数据源连接相关坐标

(mysql,mybatis-plus,druid, lombok,spring-boot-starter-web)。

 

 ③ 配置连接信息

 a7854617ead64eb7aecf84bc0fd59de5.png

④ 运行项目,查看是否启动成功

1385f54045d446f1940bd874b6a071d9.png

 

1.准备一张数据表 

2cfd287a704240228cf15fe3c1b7af56.png

在此用一张学生信息表做演示,为了生成可读性更好的代码最好写"表注释"。

2.在IntelliJ IDEA中下载EasyCode插件

2f9fd514fd754ffdbb31d81c181b2832.png

 3.ItelliJ IDEA 连接数据库 

7a77fa654abd49b4b2e47977d8d9565b.png

 19c15b025d9f4277b79bbbfe002ac3a8.png

 4.选择表,生成代码。

ab8fa7f255d248f980cb6774d383545c.png

 d697526be0514e1fa89cd6d8c5cbebef.png

可用多选数据表,一起生成。 

-- 弹窗勾选,点击ok。

 5b0c4c397d4f4ad1b9f8f853b8e3b641.png

 99f79b5592564df7beb1b3222d8365d3.png

至此,代码就生成完毕了。

** 但是,后端还缺少联调对象R,和分页拦截器的配置类没有生成,在下方会有提供。

请根据自身习惯放到目录结构中。

前端组件可以直接放到vue的项目中注册引用。

生成的前端组件展示

0f085b06731547fcb0ca4937b45069cf.png

总结:我们只需要有一张数据表,那么通过此插件和模板,就能够根据表字段自动生成MyBatisPlus格式的后端基本增删改分页查接口,以及生成一个前端增删改分页查可用的组件,简化了开发和减少了我们重复性的工作。 

模板代码 

如下两个类,请自己放到自定义目录文件中。一个是R.java,用于前后端数据联调的,一个是MyBatisPlusConfig.java,里面配置了分页拦截器,用于实现分页查询功能。

放到目录中哪问题不大,其他文件能引用即可。

 数据联调对象R 

@Data
public class R<T> {
        private Integer code; //编码:1成功,0和其它数字为失败

        private String msg; //错误信息

        private T data; //数据

        public static <T> R<T> success(T object) {
            R<T> r = new R<T>();
            r.data = object;
            r.code = 1;
            return r;
        }

        public static <T> R<T> error(String msg) {
            R r = new R();
            r.msg = msg;
            r.code = 0;
            return r;
        }
}

分页拦截器的配置

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        // 创建拦截器对象
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 添加分页拦截器
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}

模板结构 (没有就创建,然后复制粘贴)

88a28c468add46d999170c26e508008a.png

  实体类pojo 

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

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

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

##自动导入包(全局变量)
$!{autoImport.vm}
import com.baomidou.mybatisplus.extension.activerecord.Model;
import java.io.Serializable;
import lombok.Data;

##表注释(宏定义)
#tableComment("表实体类")
@SuppressWarnings("serial")
@Data
public class $!{tableInfo.name} {
#foreach($column in $tableInfo.fullColumn)
    #if(${column.comment})//${column.comment}#end

    private $!{tool.getClsNameByFullName($column.type)} $!{column.name};
#end
}

 表现层controller

##导入宏定义
$!{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.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import $!{tableInfo.savePackageName}.pojo.$!tableInfo.name;
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
@Slf4j
@CrossOrigin
@RequestMapping("/$!tool.firstLowerCase($!tableInfo.name)s")
public class $!{tableName} {
    /**
     * 服务对象
     */
    @Autowired
    private $!{tableInfo.name}Service $!{serviceName};

     /**
   * 分页查询
   * @param page 查询页数
   * @param size 一页显示条数
   * @return ·
   */
   @GetMapping("/page")
   public R<Page<$!{tableInfo.name}>> getAllByPage(int page, int size){
   	Page<$!{tableInfo.name}> $!tool.firstLowerCase($!tableInfo.name)Page = new Page<>(page, size);
   	LambdaQueryWrapper<$!{tableInfo.name}> queryWrapper = new LambdaQueryWrapper<>();
   	//TODO 查询条件定制
   
   	//执行查询
   	$!{serviceName}.page($!tool.firstLowerCase($!tableInfo.name)Page);
   	return R.success($!tool.firstLowerCase($!tableInfo.name)Page);
   }

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

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

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

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable("id") String id) {
        return R.success(this.$!{serviceName}.removeById(id) + "");
    }
}

业务层service接口

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

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

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

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

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

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

}

 业务层serviceImpl实现类

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

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

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

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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import $!{tableInfo.savePackageName}.dao.$!{tableInfo.name}Dao;
import $!{tableInfo.savePackageName}.pojo.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.stereotype.Service;

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

}

持久层dao

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

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

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

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

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import $!{tableInfo.savePackageName}.pojo.$!tableInfo.name;
import org.apache.ibatis.annotations.Mapper;
##表注释(宏定义)
#tableComment("表数据库访问层")
@Mapper
public interface $!{tableName} extends BaseMapper<$!tableInfo.name> {

}

Vue组件 

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

##保存文件(宏定义)
#save("/vueConponent", "vueConponent.vue")
<!-- 基于$!{tableInfo.name}表的基础增删改查组件 -->
<template>
	<div id="container">
		<!-- 新增按钮 -->
		<el-button type="primary" @click="addRow">新增</el-button>
		<!-- 表格 -->
		<el-table :data="tableData" style="width: 100%" stripe>
			<el-table-column 
				v-for="(item, index) in tableTitle" 
				:key="index"
				:prop="item.prop"
				:label="item.label"
				>
			</el-table-column>
			
			<el-table-column label="操作">
				<template slot-scope="scope">
					<el-button type="text" @click="editRow(scope.$index, scope.row)">编辑</el-button>
					<el-button type="text" @click="deleteRow(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 编辑/新增对话框 -->
		<el-dialog :visible.sync="dialogVisible" title="编辑/新增" @close="closeDialog">
			<el-form ref="form" :model="currentRow" :rules="formRules" label-width="80px">
				<el-form-item v-for="(item, index) in tableTitle"
							:key="index" 
							:rules="formRules"
							:label="item.label" 
							:prop="item.prop">
					<el-input v-model="currentRow[item.prop]"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeDialog">取消</el-button>
				<el-button type="primary" @click="saveRow">保存</el-button>
			</div>
		</el-dialog>
		<!-- 分页组件 -->
		<el-pagination 
			@size-change="handleSizeChange" 
			@current-change="handleCurrentChange"
			:current-page.sync="currentPage" 
			:page-size="pageSize"
			layout="total, prev, pager, next" 
			:total="total">
		</el-pagination>
	</div>
</template>
<script>
	import axios from 'axios';
	export default {
		data() {
			return {
				// 表格标题
				tableTitle:[
		    #foreach($column in $tableInfo.fullColumn)
			   {prop:"$!{column.name}",label:"#if(${column.comment})${column.comment}#else$!{column.name} #end"},
			  #end
			],
				tableData: [], // 表格数据
				dialogVisible: false, // 新增/编辑框是否出现
				currentRow: {}, // 当前编辑的行数据
				// 分页组件相关数据
				//当前显示页
				currentPage: 1, 
				// 每页显示条数
				pageSize:10,
				// 总条数
				total:100,
				// 判断弹出的模态框是否是新增
				isAddFlag:false,
				// 表单校验规则-必填
				formRules: [
					{ required: true, message: '该字段不能为空', trigger: 'blur' }
				]
			};
		},
		mounted(){
			// 获取表格数据(分页查询)
			this.getTableData();
		},
		methods: {
			// 获取表格数据(分页查询)
			async getTableData(){
				// 封装请求参数
				// 拼接条件参数(默认查询第1页的10条数据)
				const param = `page=${this.currentPage}&size=${this.pageSize}`;
				const {data: {data: res}} = await axios.get("http://localhost:8066/$!{tool.firstLowerCase($!tableInfo.name)}s/page?" + param);
				this.tableData = res.records;
				this.total = res.total;
			},
			// 分页组件-改变size
			handleSizeChange(val) {
				this.pageSize = val;
				this.getTableData();
			},
			// 分页组件-改变page
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getTableData();
			},
			// 添加按钮触发
			addRow() {
				this.isAddFlag = true;
				this.currentRow = {};
				this.dialogVisible = true;
			},
			// 编辑按钮触发
			editRow(index, row) {
				this.isAddFlag = false;
				this.currentRow = {
					...row
				};
				this.dialogVisible = true;
			},
			// 删除按钮触发
			async deleteRow(row) {
				if(!confirm("永久删除此条数据, 是否继续?")){
					this.$message({
						type: 'info',
						message: '已取消删除'
					});    
					return false;
				}
				// 确定删除,根据uid删除
				const res = await axios.delete("http://localhost:8066/$!{tool.firstLowerCase($!tableInfo.name)}s/" + row.uid)
				
				// TODO 自定义判断状态
				
				this.$message.success("删除成功!"); // 成功提示
				// 处理删除页最后一个数据不跳转上一页问题
				if(this.tableData.length - 1 == 0 && this.currentPage != 1){
					this.currentPage -= 1;
				}
				this.getTableData(); // 重新获取表格数据
			},
			// 关闭"新增/编辑框"
			closeDialog() {
				this.dialogVisible = false;
			},
			// 新增/编辑框内点击"保存"按钮
			async saveRow() {
			    // 验证表单,是否输入为空
				const valid = await this.$refs.form.validate();
				if (!valid) {
					return false;
				}
				// 判断当前模态框是否是"添加"模态框
				if(this.isAddFlag){
					// 添加逻辑
					const res = await axios.post("http://localhost:8066/$!{tool.firstLowerCase($!tableInfo.name)}s", this.currentRow);
					// TODO自定义判断返回,是否成功。
					
					this.$message.success("添加成功!"); // 成功提示。
					this.getTableData(); // 重新获取数据
					this.dialogVisible = false; // 关闭新增窗口
				}else{
					// 编辑逻辑
					const res = await axios.put("http://localhost:8066/$!{tool.firstLowerCase($!tableInfo.name)}s", this.currentRow);
					// TODO自定义判断返回,是否成功。
					
					this.$message.success("修改成功!"); // 成功提示。
					this.getTableData(); // 重新获取数据
					this.dialogVisible = false; // 关闭修改窗口
				}
			}
		}
	};
</script>

<style scoped>
	
</style>

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mao.O

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值