简述
创建一个vue 脚手架项目并安装,配置plop
安装:npm install plop
修改vue配置:启动方式
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"plop": "plop"
},
vue根目录创建一个plop入口文件:plopfile.js
const springGenerator = require('./plop-templates/spring/prompt'); //指定一个模块目录(根据自己目录)
module.exports = function (plop) {
plop.setGenerator('spring', springGenerator);//引入模块,可以多个
//如果模块多个,启动时,控制台可以选择
};
根目录创建一个plop-templates文件夹—>spring文件夹
const { notEmpty } = require('../utils') // 自己定义的一个工具方法-后面会说
// 导入数据
const json = require('./config.json')
module.exports = {
description: '自动按模板生成 spirng后端接口代码', // 描述这个generate的作用
prompts: [
{
type: 'input', // 问题的类型
name: 'fileName', // 问题对应得到答案的变量名,可以在acitons中使用该变量
message: '请输入模块名:', // 在命令行中的问题
validate: notEmpty('fileName') // 验证输入的值,notEmpty自定义的工具方法里验证
}
// 这里可以多个,代表多个问题,依次执行
/** {
type: 'input', // 问题的类型
name: 'pathName2', // 问题对应得到答案的变量名,可以在acitons中使用该变量
message: '文件名称2' // 在命令行中的问题
}**/
],
// 执行的动作
actions: (data) => {
// 这里可以通过data获取输入的fileName
const actions = [
// 创建index.js文件
{
type: 'add', // 操作类型 添加文件
path: `src/${data.fileName}/${data.fileName}Entity.java`, // 添加的文件的路径
templateFile: 'plop-templates/spring/entity.hbs', // 模版文件的路径(***这里就是想要生成的模板)
data: {
entity: json.entity,
module: json.module,
Module: json.Module
}
},
{
type: 'add', // 操作类型 添加文件
path: `src/${data.fileName}/${data.fileName}Dao.java`, // 添加的文件的路径
templateFile: 'plop-templates/spring/dao.hbs', // 模版文件的路径(***这里就是想要生成的模板)
data: {
entity: json.entity,
module: json.module,
Module: json.Module
}
},
{
type: 'add', // 操作类型 添加文件
path: `src/${data.fileName}/${data.fileName}Service.java`, // 添加的文件的路径
templateFile: 'plop-templates/spring/service.hbs', // 模版文件的路径(***这里就是想要生成的模板)
data: {
entity: json.entity,
module: json.module,
Module: json.Module
}
},
{
type: 'add', // 操作类型 添加文件
path: `src/${data.fileName}/${data.fileName}Controller.java`, // 添加的文件的路径
templateFile: 'plop-templates/spring/controller.hbs', // 模版文件的路径(***这里就是想要生成的模板)
data: {
entity: json.entity,
module: json.module,
Module: json.Module
}
}
]
return actions
}
}
{
"entity": [
{ "label": "值", "key": "value", "Key": "Value", "type": "String", "nullable": "false" },
{ "label": "备注", "key": "note", "Key": "Note", "type": "String", "nullable": "false" }
],
"Module": "Test",
"module": "test"
}
@Entity
@Table(name = "tb_{{module}}")
@Data
//数据
public class {{Module}}Entity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id = 0;
{{#each entity}}
@Column{{#if this.nullable }} (nullable = false) {{/if}}
{{this.type}} {{this.key}} {{#if this.nullable }} = ""{{/if}};
{{/each}}
}
#earch:循环数组,并默认this属于子项
#if:条件语句
具体 Express模板引擎定制—hbs 的资料
jap可以通过实体类,自动生成数据库表格
生成后
@Entity @Table(name = "tb_test") @Data //数据 public class TestEntity implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) int id = 0; @Column(nullable = false) String value = ""; @Column(nullable = false) String note = ""; }
public interface {{Module}}Dao extends JpaRepository<{{Module}}Entity,Integer> {
//根据id批量删除
void delete{{Module}}EntitiesByIdIn(List<Integer> {{module}}Ids);
//批量查询+分页+模糊
List<{{Module}}Entity> findAllBy{{#each entity}}{{this.Key}}ContainingAnd{{/each}} ({{#each entity}}String {{this.key}},{{/each}}Pageable p);
//根据条件查询总数
Integer countAllBy{{#each entity}}{{this.Key}}ContainingAnd{{/each}} ({{#each entity}}String {{this.key}},{{/each}});
}
生成后
public interface TestDao extends JpaRepository<TestEntity,Integer> { //根据id批量删除 void deleteTestEntitiesByIdIn(List<Integer> testIds); //批量查询+分页+模糊 List<TestEntity> findAllByValueContainingAndNoteContaining (String value, String note, Pageable p); //根据条件查询总数 Integer countAllByValueContainingAndNoteContaining (String value,String note); }
模板service.hbs
@Service
public class {{Module}}Service {
@Autowired
{{Module}}Dao {{module}}Dao;
//查询+模糊
public Map<String, Object> get{{Module}}AllService( Map<String,Object> map) {
//获取相应参数
Integer page = (Integer) map.getOrDefault("page",1);
Integer pageSize = (Integer) map.getOrDefault("pageSize",10);
String sort = (String) map.getOrDefault("sort","DESC");
String sortKey = (String) map.getOrDefault("sortKey","id");
{{#each entity}}
{{this.type}} {{this.key}} = ({{this.type}}) map.getOrDefault("{{this.key}}","");
{{/each}}
Sort sortObj = Sort.by(MyUtils.getSort(sort), sortKey);
Pageable pageable = PageRequest.of(page-1, pageSize,sortObj);
List<{{Module}}Entity> allContains = {{module}}Dao.findAllBy{{#each entity}}{{this.Key}}ContainingAnd{{/each}} ({{#each entity}} {{this.key}},{{/each}}pageable);
Map<String,Object> returnMap = new HashMap<>();
returnMap.put("size",{{module}}Dao.countAllBy{{#each entity}}{{this.Key}}ContainingAnd{{/each}} ({{#each entity}} {{this.key}},{{/each}}));
returnMap.put("list",allContains);
return ReturnDateUtil.returnData(ReturnDateUtil.CODE_OK, "获取成功!", returnMap);
}
//批量删除
@Transactional
public Map<String, Object> delete{{Module}}Service( List<Integer> {{module}}Ids) {
{{module}}Dao.delete{{Module}}EntitiesByIdIn({{module}}Ids);
return ReturnDateUtil.returnData(ReturnDateUtil.CODE_OK, "删除成功!", {{module}}Ids.size());
}
//保存-修改
public Map<String, Object> save{{Module}}Service( {{Module}}Entity {{module}}Entity) {
//判断是否添加还是修改
boolean isAdd = {{module}}Entity.getId() == 0;
//如果是添加
{{Module}}Entity save = {{module}}Dao.save({{module}}Entity);
return ReturnDateUtil.returnData(ReturnDateUtil.CODE_OK, isAdd ? "添加成功!" : "修改成功!", save);
}
}
生成后
@Service public class TestService { @Autowired TestDao testDao; //查询+模糊 public Map<String, Object> getTestAllService( Map<String,Object> map) { //获取相应参数 Integer page = (Integer) map.getOrDefault("page",1); Integer pageSize = (Integer) map.getOrDefault("pageSize",10); String sort = (String) map.getOrDefault("sort","DESC"); String sortKey = (String) map.getOrDefault("sortKey","id"); String value = (String) map.getOrDefault("value",""); String note = (String) map.getOrDefault("note",""); Sort sortObj = Sort.by(MyUtils.getSort(sort), sortKey); Pageable pageable = PageRequest.of(page-1, pageSize,sortObj); List<TestEntity> allContains = testDao.findAllByValueContainingAndNoteContaining ( value, note,pageable); Map<String,Object> returnMap = new HashMap<>(); returnMap.put("size",testDao.countAllByValueContainingAndNoteContaining ( value, note)); returnMap.put("list",allContains); return ReturnDateUtil.returnData(ReturnDateUtil.CODE_OK, "获取成功!", returnMap); } //批量删除 @Transactional public Map<String, Object> deleteTestService( List<Integer> testIds) { testDao.deleteTestEntitiesByIdIn(testIds); return ReturnDateUtil.returnData(ReturnDateUtil.CODE_OK, "删除成功!", testIds.size()); } //保存-修改 public Map<String, Object> saveTestService( TestEntity testEntity) { //判断是否添加还是修改 boolean isAdd = testEntity.getId() == 0; //如果是添加 TestEntity save = testDao.save(testEntity); return ReturnDateUtil.returnData(ReturnDateUtil.CODE_OK, isAdd ? "添加成功!" : "修改成功!", save); } }
模板controller
@RestController
@RequestMapping("/{{module}}")
@Slf4j
public class {{Module}}Controller {
@Autowired
{{Module}}Service {{module}}Service;
//----
@PostMapping("/get{{Module}}All")
@ApiImplicitParams({
@ApiImplicitParam(value = "当前页", name = "page", required = true),
@ApiImplicitParam(value = "一页多少个", name = "pageSize", required = true),
@ApiImplicitParam(value = "升降序", name = "sort", required = true),
@ApiImplicitParam(value = "升降序的键", name = "sortKey", required = true),
})
public Map<String, Object> get{{Module}}All(@RequestBody(required = false) Map<String,Object> map) {
log.debug("-------------------getUserAll:获取全部{{Module}}-------------");
return {{module}}Service.get{{Module}}AllService(map);
}
@PostMapping("/delete{{Module}}")
//必传参数,提示客户端
@ApiImplicitParams({
@ApiImplicitParam(value = "唯一id", name = "{{module}}Ids", required = true),
})
public Map<String, Object> delete{{Module}}(@RequestBody(required = false) Map<String, List<Integer>> map) {
log.debug("-------------------getUserAll:获取全部{{Module}}-------------");
List<Integer> {{module}}Ids = map.get("{{module}}Ids");
return {{module}}Service.delete{{Module}}Service( {{module}}Ids);
}
@PostMapping("/save{{Module}}")
public Map<String, Object> save{{Module}}(@RequestBody(required = false) {{Module}}Entity {{module}}Entity) {
log.debug("-------------------PostMapping:添加{{Module}}-------------");
return {{module}}Service.save{{Module}}Service({{module}}Entity);
}
}
生成后
@RestController @RequestMapping("/test") @Slf4j public class TestController { @Autowired TestService testService; //---- @PostMapping("/getTestAll") @ApiImplicitParams({ @ApiImplicitParam(value = "当前页", name = "page", required = true), @ApiImplicitParam(value = "一页多少个", name = "pageSize", required = true), @ApiImplicitParam(value = "升降序", name = "sort", required = true), @ApiImplicitParam(value = "升降序的键", name = "sortKey", required = true), }) public Map<String, Object> getTestAll(@RequestBody(required = false) Map<String,Object> map) { log.debug("-------------------getUserAll:获取全部Test-------------"); return testService.getTestAllService(map); } @PostMapping("/deleteTest") //必传参数,提示客户端 @ApiImplicitParams({ @ApiImplicitParam(value = "唯一id", name = "testIds", required = true), }) public Map<String, Object> deleteTest(@RequestBody(required = false) Map<String, List<Integer>> map) { log.debug("-------------------getUserAll:获取全部Test-------------"); List<Integer> testIds = map.get("testIds"); return testService.deleteTestService( testIds); } @PostMapping("/saveTest") public Map<String, Object> saveTest(@RequestBody(required = false) TestEntity testEntity) { log.debug("-------------------PostMapping:添加Test-------------"); return testService.saveTestService(testEntity); } }
plop-templates文件夹->utils.js
//简单的验证下,输入的值
//返回string:代表有错误信息,会显示再控制台
//热会true:代表通过
exports.notEmpty = (name) => {
return (v) => {
if (!v || v.trim === '') {
return `${name}为必填项`
} else {
return true
}
}
}
<!-- web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 红辣椒:自动get/set(这个插件需要idea需要安装插件才能使用) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<!-- 数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>