SpringBoot项目实战(37)--使用Beetl模板实现代码生成器(六)-- 完整的Mybatis-plus低代码生成程序并支持Swagger
本文介绍了基于beetl模版实现Mybatis-plus增删改查代码的完整实现,包括实体类、参数类、Mapper类、Mapper.xml文件、Service类、接口类模版和低代码生成,可指定一个数据库表一键生成上面的所有的代码,并且支持Swagger注解生成开发文档,功能非常强大,用到项目开发中会起到事半功倍的效果。
在上文中介绍了Mybatis-plus增删改查的整套代码。本文利用上文的整套代码改造Beetl代码模版,并依据这些模版,选择一个数据库表生成增删改查相关的程序代码。
一、数据库表
因为上文用了comm_api_key作为代码模板,已经有了一套示例代码,本文使用另外的数据库表实现增删改查功能。我们使用短信商管理表作为示例,短信商表存储不同的短信供应商的配置信息:
CREATE TABLE `sms_supplier` (
`row_id` varchar(40) NOT NULL COMMENT '唯一ID',
`sort_no` bigint(20) DEFAULT NULL COMMENT '记录顺序',
`create_dt` varchar(23) DEFAULT NULL COMMENT '创建日期',
`update_dt` varchar(23) DEFAULT NULL COMMENT '修改日期',
`create_uid` varchar(32) DEFAULT NULL COMMENT '创建人',
`update_uid` varchar(32) DEFAULT NULL COMMENT '修改人',
`data_flg` varchar(6) DEFAULT NULL COMMENT '状态位',
`obj_name` varchar(40) DEFAULT NULL COMMENT '备注',
`master_row_id` varchar(40) DEFAULT NULL COMMENT '父表ID',
`flow_trans_id` varchar(40) DEFAULT NULL COMMENT '事务ID',
`flow_status` varchar(16) DEFAULT NULL COMMENT '流程状态',
`record_version` bigint(20) NOT NULL COMMENT '乐观锁',
`is_default` varchar(10) DEFAULT NULL COMMENT '是否默认',
`sup_name` varchar(100) DEFAULT NULL COMMENT '短信商名称',
`recv_msg_url` varchar(255) DEFAULT NULL COMMENT '接收消息URL',
`query_balance_url` varchar(255) DEFAULT NULL COMMENT '查询余额URL',
`chg_pass_url` varchar(255) NOT NULL COMMENT '修改密码URL',
`send_mess_url` varchar(255) NOT NULL COMMENT '发送短信URL',
`abbr_name` varchar(40) DEFAULT NULL COMMENT '短信商简称',
`interface_addr` varchar(100) DEFAULT NULL COMMENT '接口地址',
`sup_code` varchar(40) NOT NULL COMMENT '短信商编码',
`province_id` varchar(10) DEFAULT NULL COMMENT '省份',
`home_page` varchar(100) DEFAULT NULL COMMENT '主页',
`regist_child_url` varchar(400) DEFAULT NULL COMMENT '注册子账号URL',
`encoding_type` varchar(10) DEFAULT NULL COMMENT '接口字符集',
`filter_words_url` varchar(255) DEFAULT NULL COMMENT '敏感词URL',
`recv_sms_url` varchar(255) DEFAULT NULL COMMENT '收短信URL',
`error_url` varchar(200) DEFAULT NULL COMMENT '错误信息URL',
PRIMARY KEY (`row_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='短信供应商表';
-- ----------------------------
-- Records of sms_supplier
-- ----------------------------
INSERT INTO `sms_supplier` VALUES ('0c63fa49211b492097bc3ff5a14720f6', null, '2019-12-10 16:15:27', '2019-12-10 16:15:27', 'admin', 'admin', null, null, null, '1575965727921000893', '00', '0', null, '阿里云', null, null, '#', '#', null, '#', 'ALI', null, null, null, 'utf-8', null, null, null);
INSERT INTO `sms_supplier` VALUES ('12bfbc8297484c8f998839fb102c26f8', null, '2012-07-26 16:02:59', '2014-04-04 20:52:09', 'admin', 'admin', null, null, null, '1343289779995000750', '00', '9', 'N', 'YY', 'http://p1.ipyy.com:8888/callApi.aspx?action=query&userid=企业ID&account=用户名&password=密码', 'http://p1.ipyy.com:8888/sms.aspx?action=overage&userid=635&account=用户名&password=密码', '1', 'http://p1.ipyy.com:8888/sm1s.aspx?action=send&userid=企业ID&account=用户名&password=密码&mobile=手机号码&content=内容&sendTime=&taskName=&checkcontent=1&mobilenumber=1&countnumber=1&telephonenumber=0', 'YY', null, 'YY', '110000', null, null, 'utf-8', null, null, null);
INSERT INTO `sms_supplier` VALUES ('3eb6fc6362a84debad6e890fb9ef6b17', null, '2012-03-12 09:50:26', '2022-11-19 12:09:22', 'admin', 'admin', null, null, null, '1331517026562001455', '00', '15', 'Y', '<><>', 'http://www.sms1086.com/plan/Api/recv.aspx?username=用户名&amp;password=密码&amp;from=起始日期&amp;read=状态', 'http://www.sms1086.com/plan/Api/Query.aspx?username=用户名&amp;password=密码', 'http://www.sms1086.com/plan/Api/ChgPwd.aspx?username=用户名&amp;password=密码&amp;newpwd=新密码', 'http://www.sms1086.com/plan/Api/Send.aspx?username=用户名&amp;password=密码&amp;mobiles=手机号码&amp;content=内容&amp;f=1', 'TX', 'http://www.sms1086.com/plan/Api/', 'TX', '410000', 'http://www.sms1086.com/', 'http://www.sms1086.com/plan/api/ChildRegister.aspx?myusername=用户名&amp;mypassword=密码&amp;childusername=子用户名&amp;childpassword=子用户密码&amp;fullname=单位名称&amp;shortname=单位简称&amp;realname=联系人姓名&amp;mobile=手机&amp;tele=电话', null, '1', '1', null);
INSERT INTO `sms_supplier` VALUES ('6428f91475cf4e6d8a2276570c91508f', null, '2012-08-07 15:42:30', '2012-09-17 14:47:27', 'admin', 'admin', null, null, null, '1344325350919000758', '00', '8', null, 'YY2', 'http://ipyy.net/WS/Get.aspx?CorpID=用户名&Pwd=密码', 'http://ipyy.net/WS/SelSum.aspx?CorpID=用户名&Pwd=密码', 'http://ipyy.net/WS/UpdPwd.aspx?CorpID=用户名&Pwd=密码&NewPwd=新密码', 'http://www.ipyy.net/WS/BatchSend.aspx?CorpID=用户名&Pwd=密码&Mobile=手机号码&Content=内容&Cell=子号&SendTime=发送时间', 'YY2', null, 'YY2', '110000', null, null, 'gb2312', null, null, null);
INSERT INTO `sms_supplier` VALUES ('fd091dac7d8c4025b5b9094ed08979f3', null, '2017-07-27 14:46:24', '2017-07-27 14:46:24', 'admin', 'admin', null, null, null, '1501137984378001007', '00', '0', null, 'CL2', 'http://smssh1.253.com/msg/send/json', 'http://smssh1.253.com/msg/send/json', 'http://smssh1.253.com/msg/send/json', 'http://smssh1.253.com/msg/send/json', null, '#', 'CL2', '310000', '#', 'http://smssh1.253.com/msg/send/json', 'utf-8', 'http://smssh1.253.com/msg/send/json', null, null);
二、编写Beetl代码模板
根据前面的代码示例,我们需要做几个代码模板,包括实体类、参数类、Mapper类、Service类、Api接口类、Mapper.xml。下面分别是这几个模板,模板文件位置为open-dev的resources/templates/dev下:
2.1 实体类模板
package ${packageName};
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 功能说明:${tableDesc}
*/
@Data
@TableName("${tableName}")
public class ${entityClassName} implements java.io.Serializable {
<%
for(field in fieldList){
%>
${field.tableId}
${field.apiProperty}
${field.defaultValueExpr}
${field.fieldDeclare}
<%}%>
}
说明:在实体类模版中,还增加了Swagger文档注释的注解${field.apiProperty},生成代码时会用swagger注解替换掉变量,可以省去我们编写接口参数说明的时间。模板文件名为EntityTemplate.java。
2.2 参数类模板
package ${basePackage}.module.params;
import lombok.Data;
import ${fullEntityClassName};
@Data
public class ${entityClassName}Param extends ${entityClassName} {
private Integer page=1; //当前页
private Integer pageSize=20;//每页行数
public ${entityClassName}Param() {
page = 1;
pageSize = 20;
}
}
参数类模板文件为ParamTemplate.java。
2.3 Mapper类文件
Mapper类相当于DAO接口,需要@Mapper注解,模板文件名为MapperTemplate.java:
package ${basePackage}.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.openjweb.core.entity.CommApiKey;
import ${fullEntityClassName};
import ${basePackage}.module.params.${entityClassName}Param;
import java.util.List;
@Mapper
public interface ${entityClassName}Mapper extends BaseMapper<${entityClassName}> {
/**
* 带分页的查询
* @param page
* @param param
* @return
*/
IPage<${entityClassName}> findPage(Page<?> page, @Param("param") ${entityClassName} param );
@Select("SELECT * FROM ${tableName} WHERE row_id = #{rowId}")
${entityClassName} queryByRowId(@Param("rowId") String rowId);
/**
* 不带分页的查询
* @param param
* @return
*/
List<${entityClassName}> queryList(@Param("param") ${entityClassName}Param param);
}
2.4 Mapper.xml XML 文件模板
模板文件为MapperTemplate.xml
<?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="${basePackage}.mapper.${entityClassName}Mapper">
<select id="queryList" resultType="${fullClassName}" >
select * from ${tableName}
<where>
<%
for(field in fieldList){
%>
<if test="param.${field.fieldName} !=null ">
and ${field.columnName} = #{param.${field.fieldName}}
</if>
<%}%>
</where>
</select>
<select id="findPage" resultType="${fullClassName}" >
select * from ${tableName}
<%
for(field in fieldList){
%>
<if test="param.${field.fieldName} !=null ">
and ${field.columnName} = #{param.${field.fieldName}}
</if>
<%}%>
</select>
</mapper>
2.5 Service类文件模板
Service类文件模板为ServiceTemplate.java:
package ${basePackage}.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import ${fullClassName};
import ${basePackage}.mapper.${entityClassName}Mapper;
import ${basePackage}.module.params.${entityClassName}Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Service
@Slf4j
public class ${entityClassName}Service extends ServiceImpl<${entityClassName}Mapper, ${entityClassName}> {
@Autowired
private ${entityClassName}Mapper ${classNameLower}Mapper;
/**
* 根据ROWID查询
* @param rowId
* @return
*/
public ${entityClassName} queryByRowId(String rowId){
return this.${classNameLower}Mapper.queryByRowId(rowId);
}
public List<${entityClassName}> queryList(${entityClassName}Param param){
List list = this.${classNameLower}Mapper.queryList(param);
return list;
}
/**
* 分页查询
* @param param
* @return
*/
public IPage<${entityClassName}> findPage(${entityClassName}Param param){
Page<${entityClassName}> page = new Page<>(param.getPage(), param.getPageSize());
IPage<${entityClassName}> list = this.${classNameLower}Mapper.findPage(page,param);
return list;
}
/**
* 批量删除
* @param selectedIds
* @throws Exception
*/
public void del(String selectedIds) throws Exception {
String[] ids = null;
int delCount = 0;
if(selectedIds!=null&&selectedIds.trim().length()>0){
ids = selectedIds.split(",");
//System.out.println(ids.length);
List<String> parmList = Arrays.asList(ids);
delCount = this.${classNameLower}Mapper.deleteBatchIds(parmList);
//this.commApiKeyMapper.
}
if(delCount==0){
throw new Exception ("删除失败!");
}
}
}
2.6 Api类文件模板
Api类文件模板文件名为controllerTemplate.java:
package ${basePackage}.api;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.openjweb.common.response.ResponseResult;
import ${fullClassName};
import ${basePackage}.module.params.${entityClassName}Param;
import ${basePackage}.service.${entityClassName}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 测试:
*/
@Api(tags = "${tableDesc}")
@Slf4j
@RestController
@RequestMapping("/demo/api/${classNameLower}")
public class ${entityClassName}Api {
@Autowired
private ${entityClassName}Service ${classNameLower}Service;
/**
* 新增记录
*/
@ApiOperation("保存${tableDesc}")
@ApiImplicitParams({
<%
for(field in fieldList){ %>
@ApiImplicitParam(name = "${field.fieldName}", value = "${field.fieldNameDesc}", paramType = "query"),
<%}%>
})
@RequestMapping("/save")
public ResponseResult save( ${entityClassName}Param param){
try {
log.info("新增记录调用开始..........");
this.${classNameLower}Service.save(param);
log.info("新增记录调用结束..........");
return ResponseResult.okResult(0,"新增成功!");
}
catch(Exception ex){
ex.printStackTrace();
return ResponseResult.errorResult(-1,"新增失败!");
}
}
/**
* 新增或修改记录
* @param param
* @return
*/
@RequestMapping("saveOrUpdate")
public ResponseResult saveOrUpdate( ${entityClassName}Param param){
if(param==null){
return ResponseResult.errorResult(-1,"未传入参数.....");
}
try {
String rowId = param.getRowId();
log.info("根据rowId查询实体开始..........");
${entityClassName} ent = this.${classNameLower}Service.queryByRowId(param.getRowId());
if(ent!=null) {
//复制修改的参数
<%
for(field in fieldList){%>
ent.set${field.fieldNameUpper}(param.get${field.fieldNameUpper}());
<%}%>
this.${classNameLower}Service.updateById(ent);
}
else{
log.info("没找到实体类..,新增...");
this.${classNameLower}Service.save(param);
}
log.info("保存完毕..........");
}
catch(Exception ex){
ex.printStackTrace();
return ResponseResult.errorResult(-1,"新增失败!");
}
return ResponseResult.okResult(0,"success");
}
/**
* 查询列表不分页
* @param param
* @return
*/
@RequestMapping("query")
public ResponseResult queryList(${entityClassName}Param param ){
List<${entityClassName}> list = null;
try{
list = this.${classNameLower}Service.queryList(param);
}
catch(Exception ex){
log.error("异常::::"+ex.toString());
return ResponseResult.errorResult(-1,ex.toString());
}
return ResponseResult.okResult(list);
}
/**
* 查询单条记录
* @param rowId
* @return
*/
@RequestMapping("edit")
public ResponseResult edit(String rowId){
${entityClassName} ent = this.${classNameLower}Service.queryByRowId(rowId);
return ResponseResult.okResult(ent);
}
/**
* 分页查询
* @param param
* @return
*/
@RequestMapping("findPage")
public ResponseResult findPage(${entityClassName}Param param){
IPage<${entityClassName}> page = this.${classNameLower}Service.findPage(param);
return ResponseResult.okResult(page);
}
}
三、关于文件资源加载器和类资源加载器的编码问题及DevUtil
因为模板文件中有中文内容,所以需要确保生成的代码文件中没有乱码问题。我发现使用文件资源加载器没有乱码问题,但是使用类资源加载器有乱码问题,虽然文件本身已经转换成了utf-8字符集,而且两个加载器都设置了utf-8字符集,不知道这个是不是Beetl的BUG,下面的代码生成程序暂时都使用文件资源加载器,将文件路径指定到我们工程里模板文件的路径。openjweb-core中的DevUtil.java实现了按照上面的模板生成Java代码的功能:
package org.openjweb.dev.util;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.core.resource.FileResourceLoader;
import org.openjweb.common.util.FileUtil;
import org.openjweb.common.util.StringUtil;
import org.openjweb.core.config.BeetlConf;
import org.openjweb.dev.entity.TableColumnInfo;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.*;
@Slf4j
public class DevUtil {
private static final String BASE_PATH = "D:/project/openjweb-cloud/openjweb-dev/src/main/resources/templates";
public static List<Map<String,String>> getEntityVar(String dbDriver,String url,String schecma,String username,String password,String tableName,
String packageName) throws SQLException {
List<TableColumnInfo> list = DbUtil.getTableColumnInfo(dbDriver,url,schecma,username,password,tableName);
List<Map<String,String>> resultList = new ArrayList<>();
if(list!=null&&list.size()>0){
for(TableColumnInfo columnInfo:list){
//String
String tableId = "";
log.info("当前字段::::::");
log.info(columnInfo.getColumnName());
if(columnInfo.getColumnName().toLowerCase().equals("row_id")){
//默认ROWID为主键
tableId = "@TableId(type = IdType.ASSIGN_UUID)";
}
Map map = new HashMap();
map.put("tableId",tableId);
//生成ApiPerperty
String colDesc = columnInfo.getColumnDesc();
String colField = StringUtil.getFieldNameByColName(columnInfo.getColumnName());
map.put("apiProperty","@ApiModelProperty(value =\""+colDesc+"\" )");
//下面生成类属性定义
String colType = columnInfo.getColumnType().toLowerCase();
if(colType.indexOf("varchar")>-1||colType.indexOf("char")>-1
||colType.indexOf("text")>-1||colType.indexOf("clob")>-1 ){
colType = "String";
}
else if(colType.equals("number")||colType.endsWith("int")){
colType = "Long";//整数类型
}
else if(colType.equals("decimal")||colType.equals("numeric")){
colType = "Double";
}
String fieldDeclare = "private "+colType+" "+colField;
if(colField.equals("record_version")){
log.info("乐观锁字段..........");
fieldDeclare += " = 0L";//乐观锁字段设置默认值
}
fieldDeclare += ";";
map.put("fieldDeclare",fieldDeclare);
map.put("fieldName",colField);//类属性名
String fieldNameUpper = colField.substring(0,1).toUpperCase()+colField.substring(1);
log.info("fieldNameUpper:");
log.info(fieldNameUpper);
map.put("fieldNameUpper",fieldNameUpper);//类属性名
map.put("columnName",columnInfo.getColumnName());
map.put("fieldNameDesc",columnInfo.getColumnDesc());
//对于设置默认值的字段
String defaultValueExpr = "";
if(columnInfo.getColumnName().toLowerCase().equals("record_version")){
defaultValueExpr = "@Version";//乐观锁
}
else if(columnInfo.getColumnName().toLowerCase().equals("create_dt")){
defaultValueExpr = "@TableField(fill = FieldFill.INSERT)";//
}
else if(columnInfo.getColumnName().toLowerCase().equals("create_uid")){
defaultValueExpr = "@TableField(fill = FieldFill.INSERT)";//
}
else if(columnInfo.getColumnName().toLowerCase().equals("update_dt")){
defaultValueExpr = "@TableField(fill = FieldFill.INSERT_UPDATE)";//
}
else if(columnInfo.getColumnName().toLowerCase().equals("update_uid")){
defaultValueExpr = "@TableField(fill = FieldFill.INSERT_UPDATE)";//
}
map.put("defaultValueExpr",defaultValueExpr);
resultList.add(map);
}
}
return resultList;
}
public static String createEntityFile(String dbDriver,String url,String schecma,String username,String password,String tableName,
String packageName,String saveFilePath) throws SQLException {
List<Map<String,String>> list = DevUtil.getEntityVar(dbDriver,url,schecma, username, password, tableName,
packageName) ;
ClasspathResourceLoader cpLoader = new ClasspathResourceLoader("templates","utf-8");
FileResourceLoader fileResourceLoader = new FileResourceLoader(BASE_PATH,"utf-8");
//ClasspathResourceLoader cpLoader = new ClasspathResourceLoader("templates");
GroupTemplate gt = null;
boolean bool = true;//使用文件路径,改为false则使用resource/templates路径
Configuration cfg = null;
try {
cfg = Configuration.defaultConfiguration();
cfg.setCharset("utf-8");//设置文件的字符集
//cfg.set
} catch (IOException e) {
e.printStackTrace();
}
//gt = new GroupTemplate(cpLoader, cfg);
gt = new GroupTemplate(fileResourceLoader, cfg);
Template t = gt.getTemplate("dev/EntityTemplate.java");
//根据表名转换为类名
String entityClassName = StringUtil.getEntityNameByTableName(tableName);
log.info("表对应的类名:"+entityClassName);
String tableDesc = DbUtil.getTableComment(dbDriver,url,schecma,username,password,tableName);
log.info("表说明:");
log.info(tableDesc);
log.info("entityClassName::::");
log.info(entityClassName);
t.binding("packageName",packageName);
t.binding("tableDesc",tableDesc);
t.binding("tableName",tableName);
t.binding("entityClassName",entityClassName);
t.binding("fieldList",list);
String str = null;
try{
str = t.render();//模版中的中文昨天没乱码,怎么今天有乱码了?
}
catch(Exception ex){
ex.printStackTrace();
return "运行错误:"+ex.toString();
}
log.info("生成的文件内容:"+str);
//生成到文件
//String destFilePath = "D:\\project\\openjweb-cloud\\openjweb-dev\\src\\main\\resources\\templates\\dev\\MyDemo.java";
try {
FileUtil.str2file(str,saveFilePath,"utf-8");
/*try {
File outputFile = new File(saveFilePath);
FileWriter writer = new FileWriter(outputFile);
writer.write(str );
writer.close();
} catch (IOException e) {
e.printStackTrace();
}*/
} catch (Exception e) {
e.printStackTrace();
return "文件生成异常:"+e.toString();
}
return "";
}
public static String createParamFile(String dbDriver,String url,String schecma,String username,String password,String tableName,
String basePackage,String projectBasePath) throws SQLException {
ClasspathResourceLoader cpLoader = new ClasspathResourceLoader("templates","utf-8");
FileResourceLoader fileResourceLoader = new FileResourceLoader(BASE_PATH,"utf-8");
GroupTemplate gt = null;
boolean bool = true;//使用文件路径,改为false则使用resource/templates路径
Configuration cfg = null;
try {
cfg = Configuration.defaultConfiguration();
cfg.setCharset("utf-8");//设置文件的字符集
} catch (IOException e) {
e.printStackTrace();
}
//gt = new GroupTemplate(cpLoader, cfg);
gt = new GroupTemplate(fileResourceLoader, cfg);
Template t = gt.getTemplate("dev/ParamTemplate.java");
//根据表名转换为类名
String entityClassName = StringUtil.getEntityNameByTableName(tableName);
log.info("表对应的类名:"+entityClassName);
String tableDesc = DbUtil.getTableComment(dbDriver,url,schecma,username,password,tableName);
log.info("表说明:");
log.info(tableDesc);
log.info("entityClassName::::");
log.info(entityClassName);
String fullEntityClassName = basePackage+".entity."+entityClassName;
t.binding("basePackage",basePackage);
t.binding("fullEntityClassName",fullEntityClassName);
t.binding("entityClassName",entityClassName);
String str = null;
try{
str = t.render();
}
catch(Exception ex){
ex.printStackTrace();
return "运行错误:"+ex.toString();
}
log.info("生成的文件内容:"+str);
//生成到文件
//String destFilePath = "D:\\project\\openjweb-cloud\\openjweb-dev\\src\\main\\resources\\templates\\dev\\MyDemo.java";
String paramFileName = projectBasePath+"/"+"src/main/java/"+basePackage.replace(".","/")+"/module/params/"+entityClassName+"Param.java";
log.info("参数类位置::::");
log.info(paramFileName);
try {
FileUtil.str2file(str,paramFileName,"utf-8");
} catch (Exception e) {
e.printStackTrace();
return "文件生成异常:"+e.toString();
}
return "";
}
public static String createMapperFile(String dbDriver,String url,String schecma,String username,String password,String tableName,
String basePackage,String projectBasePath) throws SQLException {
ClasspathResourceLoader cpLoader = new ClasspathResourceLoader("templates","utf-8");
FileResourceLoader fileResourceLoader = new FileResourceLoader(BASE_PATH,"utf-8");
GroupTemplate gt = null;
boolean bool = true;//使用文件路径,改为false则使用resource/templates路径
Configuration cfg = null;
try {
cfg = Configuration.defaultConfiguration();
log.info("默认字符集:"+cfg.getCharset());
cfg.setCharset("utf-8");//设置文件的字符集
//log.info(cfg.getCharset());
} catch (IOException e) {
e.printStackTrace();
}
//gt = new GroupTemplate(cpLoader, cfg);
gt = new GroupTemplate(fileResourceLoader, cfg);
Template t = gt.getTemplate("dev/MapperTemplate.java");
//根据表名转换为类名
String entityClassName = StringUtil.getEntityNameByTableName(tableName);
log.info("表对应的类名:"+entityClassName);
String tableDesc = DbUtil.getTableComment(dbDriver,url,schecma,username,password,tableName);
log.info("表说明:");
log.info(tableDesc);
log.info("entityClassName::::");
log.info(entityClassName);
String fullEntityClassName = basePackage+".entity."+entityClassName;
t.binding("basePackage",basePackage);
t.binding("fullEntityClassName",fullEntityClassName);
t.binding("entityClassName",entityClassName);
t.binding("tableName",tableName);
String str = null;
try{
str = t.render();
}
catch(Exception ex){
ex.printStackTrace();
return "运行错误:"+ex.toString();
}
log.info("生成的文件内容:"+str);
//生成到文件
//String destFilePath = "D:\\project\\openjweb-cloud\\openjweb-dev\\src\\main\\resources\\templates\\dev\\MyDemo.java";
String paramFileName = projectBasePath+"/"+"src/main/java/"+basePackage.replace(".","/")+"/mapper/"+entityClassName+"Mapper.java";
log.info("参数类位置::::");
log.info(paramFileName);
try {
FileUtil.str2file(str,paramFileName,"utf-8");
} catch (Exception e) {
e.printStackTrace();
return "文件生成异常:"+e.toString();
}
return "";
}
public static String createXmlFile(String dbDriver,String url,String schecma,String username,String password,String tableName,
String packageName,String saveFilePath) throws SQLException {
List<Map<String,String>> list = DevUtil.getEntityVar(dbDriver,url,schecma, username, password, tableName,
packageName) ;
ClasspathResourceLoader cpLoader = new ClasspathResourceLoader("templates","utf-8");
FileResourceLoader fileResourceLoader = new FileResourceLoader(BASE_PATH,"utf-8");
//ClasspathResourceLoader cpLoader = new ClasspathResourceLoader("templates");
GroupTemplate gt = null;
boolean bool = true;//使用文件路径,改为false则使用resource/templates路径
Configuration cfg = null;
try {
cfg = Configuration.defaultConfiguration();
cfg.setCharset("utf-8");//设置文件的字符集
//cfg.set
} catch (IOException e) {
e.printStackTrace();
}
//gt = new GroupTemplate(cpLoader, cfg);
gt = new GroupTemplate(fileResourceLoader, cfg);
Template t = gt.getTemplate("dev/MapperTemplate.xml");
//根据表名转换为类名
String entityClassName = StringUtil.getEntityNameByTableName(tableName);
log.info("表对应的类名:"+entityClassName);
String tableDesc = DbUtil.getTableComment(dbDriver,url,schecma,username,password,tableName);
log.info("表说明:");
log.info(tableDesc);
log.info("entityClassName::::");
log.info(entityClassName);
//截取basePackage
t.binding("basePackage",packageName.replace(".entity",""));
t.binding("fullClassName",packageName+"."+entityClassName);
t.binding("packageName",packageName);
t.binding("tableDesc",tableDesc);
t.binding("tableName",tableName);
t.binding("entityClassName",entityClassName);
t.binding("fieldList",list);
String str = null;
try{
str = t.render();//模版中的中文昨天没乱码,怎么今天有乱码了?
}
catch(Exception ex){
ex.printStackTrace();
return "运行错误:"+ex.toString();
}
log.info("生成的文件内容:"+str);
//生成到文件
//String destFilePath = "D:\\project\\openjweb-cloud\\openjweb-dev\\src\\main\\resources\\templates\\dev\\MyDemo.java";
try {
FileUtil.str2file(str,saveFilePath,"utf-8");
/* 这个不一定支持层级目录自动创建
try {
File outputFile = new File(saveFilePath);
FileWriter writer = new FileWriter(outputFile);
writer.write(str );
writer.close();
} catch (IOException e) {
e.printStackTrace();
}*/
} catch (Exception e) {
e.printStackTrace();
return "文件生成异常:"+e.toString();
}
return "";
}
public static String createServiceFile(String dbDriver,String url,String schecma,String username,String password,String tableName,
String packageName,String saveFilePath) throws SQLException {
List<Map<String,String>> list = DevUtil.getEntityVar(dbDriver,url,schecma, username, password, tableName,
packageName) ;
ClasspathResourceLoader cpLoader = new ClasspathResourceLoader("templates","utf-8");
FileResourceLoader fileResourceLoader = new FileResourceLoader(BASE_PATH,"utf-8");
//ClasspathResourceLoader cpLoader = new ClasspathResourceLoader("templates");
GroupTemplate gt = null;
boolean bool = true;//使用文件路径,改为false则使用resource/templates路径
Configuration cfg = null;
try {
cfg = Configuration.defaultConfiguration();
cfg.setCharset("utf-8");//设置文件的字符集
//cfg.set
} catch (IOException e) {
e.printStackTrace();
}
//gt = new GroupTemplate(cpLoader, cfg);
gt = new GroupTemplate(fileResourceLoader, cfg);
Template t = gt.getTemplate("dev/ServiceTemplate.java");
//根据表名转换为类名
String entityClassName = StringUtil.getEntityNameByTableName(tableName);
log.info("表对应的类名:"+entityClassName);
String tableDesc = DbUtil.getTableComment(dbDriver,url,schecma,username,password,tableName);
log.info("表说明:");
log.info(tableDesc);
log.info("entityClassName::::");
log.info(entityClassName);
//截取basePackage
t.binding("basePackage",packageName.replace(".entity",""));
t.binding("fullClassName",packageName+"."+entityClassName);
t.binding("packageName",packageName);
t.binding("classNameLower",entityClassName.substring(0,1).toLowerCase()+entityClassName.substring(1));
t.binding("tableDesc",tableDesc);
t.binding("tableName",tableName);
t.binding("entityClassName",entityClassName);
t.binding("fieldList",list);
String str = null;
try{
str = t.render();//模版中的中文昨天没乱码,怎么今天有乱码了?
}
catch(Exception ex){
ex.printStackTrace();
return "运行错误:"+ex.toString();
}
log.info("生成的文件内容:"+str);
//生成到文件
//String destFilePath = "D:\\project\\openjweb-cloud\\openjweb-dev\\src\\main\\resources\\templates\\dev\\MyDemo.java";
try {
FileUtil.str2file(str,saveFilePath,"utf-8");
/*try {
File outputFile = new File(saveFilePath);
FileWriter writer = new FileWriter(outputFile);
writer.write(str );
writer.close();
} catch (IOException e) {
e.printStackTrace();
}*/
} catch (Exception e) {
e.printStackTrace();
return "文件生成异常:"+e.toString();
}
return "";
}
public static String createApiFile(String dbDriver,String url,String schecma,String username,String password,String tableName,
String packageName,String saveFilePath) throws SQLException {
log.info("生成Controller..............");
List<Map<String,String>> list = DevUtil.getEntityVar(dbDriver,url,schecma, username, password, tableName,
packageName) ;
ClasspathResourceLoader cpLoader = new ClasspathResourceLoader( "templates","utf-8");
FileResourceLoader fileResourceLoader = new FileResourceLoader(BASE_PATH,"utf-8");
cpLoader.setCharset("UTF-8");
//ClasspathResourceLoader cpLoader = new ClasspathResourceLoader("templates");
GroupTemplate gt = null;
boolean bool = true;//使用文件路径,改为false则使用resource/templates路径
Configuration cfg = null;
try {
cfg = Configuration.defaultConfiguration();
cfg.setCharset("utf-8");//设置文件的字符集
} catch (IOException e) {
e.printStackTrace();
}
//FileResourceLoader fileResourceLoader = new FileResourceLoader("D:\\project\\openjweb-cloud\\openjweb-dev\\src\\main\\resources\\templates\\","utf-8");
//gt = new GroupTemplate(cpLoader, cfg);
gt = new GroupTemplate(fileResourceLoader, cfg);
Template t = gt.getTemplate("dev/ControllerTemplate.java");
//根据表名转换为类名
String entityClassName = StringUtil.getEntityNameByTableName(tableName);
log.info("表对应的类名:"+entityClassName);
String tableDesc = DbUtil.getTableComment(dbDriver,url,schecma,username,password,tableName);
log.info("表说明:");
log.info(tableDesc);
log.info("entityClassName::::");
log.info(entityClassName);
//截取basePackage
t.binding("basePackage",packageName.replace(".entity",""));
t.binding("fullClassName",packageName+"."+entityClassName);
t.binding("packageName",packageName);
t.binding("classNameLower",entityClassName.substring(0,1).toLowerCase()+entityClassName.substring(1));
t.binding("tableDesc",tableDesc);
t.binding("tableName",tableName);
t.binding("entityClassName",entityClassName);
t.binding("fieldList",list);
String str = null;
try{
/* try (FileOutputStream fileOutputStream = new FileOutputStream(saveFilePath)) {
t.renderTo(fileOutputStream);
}
catch(Exception ex){}*/
str = t.render();//模版中的中文昨天没乱码,怎么今天有乱码了?
}
catch(Exception ex){
ex.printStackTrace();
return "运行错误:"+ex.toString();
}
log.info("生成的文件内容:"+str);
//生成到文件
//String destFilePath = "D:\\project\\openjweb-cloud\\openjweb-dev\\src\\main\\resources\\templates\\dev\\MyDemo.java";
try {
FileUtil.str2file(str,saveFilePath,"utf-8");
/*try {
File outputFile = new File(saveFilePath);
FileWriter writer = new FileWriter(outputFile);
writer.write(str );
writer.close();
} catch (IOException e) {
e.printStackTrace();
}*/
} catch (Exception e) {
e.printStackTrace();
return "文件生成异常:"+e.toString();
}
return "";
}
}
四、运行测试类(openjweb-sys工程中的testCreateEntity):
package org.openjweb.sys.testcase;
import lombok.extern.slf4j.Slf4j;
import org.openjweb.common.util.StringUtil;
import org.openjweb.dev.util.DevUtil;
import org.openjweb.sys.OpenjwebSysApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.testng.annotations.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
import java.sql.SQLException;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = OpenjwebSysApplication.class)
public class TestCreateEntity {
private static String tableName = "sms_supplier";
@Test
public void createAllFile() throws SQLException {
String url = "jdbc:mysql://localhost:3306/erp?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
String username = "root";
String password = "root";
String schemaName = "erp";
//String tableName = "comm_api_key";
//String tableName = "comm_system_parms";
String clsName = StringUtil.getEntityNameByTableName(tableName);
DevUtil.createEntityFile("com.mysql.jdbc.Driver",url,schemaName,username,password,tableName,"org.openjweb.core.entity","D:/project/openjweb-cloud/openjweb-core/src/main/java/org/openjweb/core/entity/"+clsName+".java");
DevUtil.createParamFile("com.mysql.jdbc.Driver",url,schemaName,username,password,tableName,"org.openjweb.core","D:/project/openjweb-cloud/openjweb-core");
DevUtil.createMapperFile("com.mysql.jdbc.Driver",url,schemaName,username,password,tableName,"org.openjweb.core","D:/project/openjweb-cloud/openjweb-core");
DevUtil.createXmlFile("com.mysql.jdbc.Driver",url,schemaName,username,password,tableName,"org.openjweb.core.entity","D:/project/openjweb-cloud/openjweb-core/src/main/java/org/openjweb/core/mapper/mapping/"+clsName+"Mapper.xml");
DevUtil.createServiceFile("com.mysql.jdbc.Driver",url,schemaName,username,password,tableName,"org.openjweb.core.entity","D:/project/openjweb-cloud/openjweb-core/src/main/java/org/openjweb/core/service/"+clsName+"Service.java");
DevUtil.createApiFile("com.mysql.jdbc.Driver",url,schemaName,username,password,tableName,"org.openjweb.core.entity","D:/project/openjweb-cloud/openjweb-core/src/main/java/org/openjweb/core/api/"+clsName+"Api.java");
}
}
在createAllFile方法中,依次生成实体类、实体参数类、Mapper类、Service类、API接口类,生成顺序是按照代码依赖关系生成的。运行后我们可以看到在openjweb-core工程中生成的源码:
实体类源码,带Swagger接口注解:
package org.openjweb.core.entity;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 功能说明:短信供应商表
*/
@Data
@TableName("sms_supplier")
public class SmsSupplier implements java.io.Serializable {
@TableId(type = IdType.ASSIGN_UUID)
@ApiModelProperty(value ="唯一ID" )
private String rowId;
@ApiModelProperty(value ="记录顺序" )
private Long sortNo;
@ApiModelProperty(value ="创建日期" )
@TableField(fill = FieldFill.INSERT)
private String createDt;
@ApiModelProperty(value ="修改日期" )
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateDt;
@ApiModelProperty(value ="创建人" )
@TableField(fill = FieldFill.INSERT)
private String createUid;
@ApiModelProperty(value ="修改人" )
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateUid;
@ApiModelProperty(value ="状态位" )
private String dataFlg;
@ApiModelProperty(value ="备注" )
private String objName;
@ApiModelProperty(value ="父表ID" )
private String masterRowId;
@ApiModelProperty(value ="事务ID" )
private String flowTransId;
@ApiModelProperty(value ="流程状态" )
private String flowStatus;
@ApiModelProperty(value ="乐观锁" )
@Version
private Long recordVersion;
@ApiModelProperty(value ="是否默认" )
private String isDefault;
@ApiModelProperty(value ="短信商名称" )
private String supName;
@ApiModelProperty(value ="接收消息URL" )
private String recvMsgUrl;
@ApiModelProperty(value ="查询余额URL" )
private String queryBalanceUrl;
@ApiModelProperty(value ="修改密码URL" )
private String chgPassUrl;
@ApiModelProperty(value ="发送短信URL" )
private String sendMessUrl;
@ApiModelProperty(value ="短信商简称" )
private String abbrName;
@ApiModelProperty(value ="接口地址" )
private String interfaceAddr;
@ApiModelProperty(value ="短信商编码" )
private String supCode;
@ApiModelProperty(value ="省份" )
private String provinceId;
@ApiModelProperty(value ="主页" )
private String homePage;
@ApiModelProperty(value ="注册子账号URL" )
private String registChildUrl;
@ApiModelProperty(value ="接口字符集" )
private String encodingType;
@ApiModelProperty(value ="敏感词URL" )
private String filterWordsUrl;
@ApiModelProperty(value ="收短信URL" )
private String recvSmsUrl;
@ApiModelProperty(value ="错误信息URL" )
private String errorUrl;
}
实体参数类源码:
package org.openjweb.core.module.params;
import lombok.Data;
import org.openjweb.core.entity.SmsSupplier;
@Data
public class SmsSupplierParam extends SmsSupplier {
private Integer page=1; //当前页
private Integer pageSize=20;//每页行数
public SmsSupplierParam() {
page = 1;
pageSize = 20;
}
}
Mapper类源码:
package org.openjweb.core.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.openjweb.core.entity.CommApiKey;
import org.openjweb.core.entity.SmsSupplier;
import org.openjweb.core.module.params.SmsSupplierParam;
import java.util.List;
@Mapper
public interface SmsSupplierMapper extends BaseMapper<SmsSupplier> {
/**
* 带分页的查询
* @param page
* @param param
* @return
*/
IPage<SmsSupplier> findPage(Page<?> page, @Param("param") SmsSupplier param );
@Select("SELECT * FROM sms_supplier WHERE row_id = #{rowId}")
SmsSupplier queryByRowId(@Param("rowId") String rowId);
/**
* 不带分页的查询
* @param param
* @return
*/
List<SmsSupplier> queryList(@Param("param") SmsSupplierParam param);
}
Mapper.xml源码:
<?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="org.openjweb.core.mapper.SmsSupplierMapper">
<select id="queryList" resultType="org.openjweb.core.entity.SmsSupplier" >
select * from sms_supplier
<where>
<if test="param.rowId !=null ">
and row_id = #{param.rowId}
</if>
<if test="param.sortNo !=null ">
and sort_no = #{param.sortNo}
</if>
<if test="param.createDt !=null ">
and create_dt = #{param.createDt}
</if>
<if test="param.updateDt !=null ">
and update_dt = #{param.updateDt}
</if>
<if test="param.createUid !=null ">
and create_uid = #{param.createUid}
</if>
<if test="param.updateUid !=null ">
and update_uid = #{param.updateUid}
</if>
<if test="param.dataFlg !=null ">
and data_flg = #{param.dataFlg}
</if>
<if test="param.objName !=null ">
and obj_name = #{param.objName}
</if>
<if test="param.masterRowId !=null ">
and master_row_id = #{param.masterRowId}
</if>
<if test="param.flowTransId !=null ">
and flow_trans_id = #{param.flowTransId}
</if>
<if test="param.flowStatus !=null ">
and flow_status = #{param.flowStatus}
</if>
<if test="param.recordVersion !=null ">
and record_version = #{param.recordVersion}
</if>
<if test="param.isDefault !=null ">
and is_default = #{param.isDefault}
</if>
<if test="param.supName !=null ">
and sup_name = #{param.supName}
</if>
<if test="param.recvMsgUrl !=null ">
and recv_msg_url = #{param.recvMsgUrl}
</if>
<if test="param.queryBalanceUrl !=null ">
and query_balance_url = #{param.queryBalanceUrl}
</if>
<if test="param.chgPassUrl !=null ">
and chg_pass_url = #{param.chgPassUrl}
</if>
<if test="param.sendMessUrl !=null ">
and send_mess_url = #{param.sendMessUrl}
</if>
<if test="param.abbrName !=null ">
and abbr_name = #{param.abbrName}
</if>
<if test="param.interfaceAddr !=null ">
and interface_addr = #{param.interfaceAddr}
</if>
<if test="param.supCode !=null ">
and sup_code = #{param.supCode}
</if>
<if test="param.provinceId !=null ">
and province_id = #{param.provinceId}
</if>
<if test="param.homePage !=null ">
and home_page = #{param.homePage}
</if>
<if test="param.registChildUrl !=null ">
and regist_child_url = #{param.registChildUrl}
</if>
<if test="param.encodingType !=null ">
and encoding_type = #{param.encodingType}
</if>
<if test="param.filterWordsUrl !=null ">
and filter_words_url = #{param.filterWordsUrl}
</if>
<if test="param.recvSmsUrl !=null ">
and recv_sms_url = #{param.recvSmsUrl}
</if>
<if test="param.errorUrl !=null ">
and error_url = #{param.errorUrl}
</if>
</where>
</select>
<select id="findPage" resultType="org.openjweb.core.entity.SmsSupplier" >
select * from sms_supplier
<if test="param.rowId !=null ">
and row_id = #{param.rowId}
</if>
<if test="param.sortNo !=null ">
and sort_no = #{param.sortNo}
</if>
<if test="param.createDt !=null ">
and create_dt = #{param.createDt}
</if>
<if test="param.updateDt !=null ">
and update_dt = #{param.updateDt}
</if>
<if test="param.createUid !=null ">
and create_uid = #{param.createUid}
</if>
<if test="param.updateUid !=null ">
and update_uid = #{param.updateUid}
</if>
<if test="param.dataFlg !=null ">
and data_flg = #{param.dataFlg}
</if>
<if test="param.objName !=null ">
and obj_name = #{param.objName}
</if>
<if test="param.masterRowId !=null ">
and master_row_id = #{param.masterRowId}
</if>
<if test="param.flowTransId !=null ">
and flow_trans_id = #{param.flowTransId}
</if>
<if test="param.flowStatus !=null ">
and flow_status = #{param.flowStatus}
</if>
<if test="param.recordVersion !=null ">
and record_version = #{param.recordVersion}
</if>
<if test="param.isDefault !=null ">
and is_default = #{param.isDefault}
</if>
<if test="param.supName !=null ">
and sup_name = #{param.supName}
</if>
<if test="param.recvMsgUrl !=null ">
and recv_msg_url = #{param.recvMsgUrl}
</if>
<if test="param.queryBalanceUrl !=null ">
and query_balance_url = #{param.queryBalanceUrl}
</if>
<if test="param.chgPassUrl !=null ">
and chg_pass_url = #{param.chgPassUrl}
</if>
<if test="param.sendMessUrl !=null ">
and send_mess_url = #{param.sendMessUrl}
</if>
<if test="param.abbrName !=null ">
and abbr_name = #{param.abbrName}
</if>
<if test="param.interfaceAddr !=null ">
and interface_addr = #{param.interfaceAddr}
</if>
<if test="param.supCode !=null ">
and sup_code = #{param.supCode}
</if>
<if test="param.provinceId !=null ">
and province_id = #{param.provinceId}
</if>
<if test="param.homePage !=null ">
and home_page = #{param.homePage}
</if>
<if test="param.registChildUrl !=null ">
and regist_child_url = #{param.registChildUrl}
</if>
<if test="param.encodingType !=null ">
and encoding_type = #{param.encodingType}
</if>
<if test="param.filterWordsUrl !=null ">
and filter_words_url = #{param.filterWordsUrl}
</if>
<if test="param.recvSmsUrl !=null ">
and recv_sms_url = #{param.recvSmsUrl}
</if>
<if test="param.errorUrl !=null ">
and error_url = #{param.errorUrl}
</if>
</select>
</mapper>
Service类源码:
1=
package org.openjweb.core.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.openjweb.core.entity.SmsSupplier;
import org.openjweb.core.mapper.SmsSupplierMapper;
import org.openjweb.core.module.params.SmsSupplierParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Service
@Slf4j
public class SmsSupplierService extends ServiceImpl<SmsSupplierMapper, SmsSupplier> {
@Autowired
private SmsSupplierMapper smsSupplierMapper;
/**
* 根据ROWID查询
* @param rowId
* @return
*/
public SmsSupplier queryByRowId(String rowId){
return this.smsSupplierMapper.queryByRowId(rowId);
}
public List<SmsSupplier> queryList(SmsSupplierParam param){
List list = this.smsSupplierMapper.queryList(param);
return list;
}
/**
* 分页查询
* @param param
* @return
*/
public IPage<SmsSupplier> findPage(SmsSupplierParam param){
Page<SmsSupplier> page = new Page<>(param.getPage(), param.getPageSize());
IPage<SmsSupplier> list = this.smsSupplierMapper.findPage(page,param);
return list;
}
/**
* 批量删除
* @param selectedIds
* @throws Exception
*/
public void del(String selectedIds) throws Exception {
String[] ids = null;
int delCount = 0;
if(selectedIds!=null&&selectedIds.trim().length()>0){
ids = selectedIds.split(",");
//System.out.println(ids.length);
List<String> parmList = Arrays.asList(ids);
delCount = this.smsSupplierMapper.deleteBatchIds(parmList);
//this.commApiKeyMapper.
}
if(delCount==0){
throw new Exception ("删除失败!");
}
}
}
Api接口类源码:
package org.openjweb.core.api;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.openjweb.common.response.ResponseResult;
import org.openjweb.core.entity.SmsSupplier;
import org.openjweb.core.module.params.SmsSupplierParam;
import org.openjweb.core.service.SmsSupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 测试:
*/
@Api(tags = "短信供应商表")
@Slf4j
@RestController
@RequestMapping("/demo/api/smsSupplier")
public class SmsSupplierApi {
@Autowired
private SmsSupplierService smsSupplierService;
/**
* 新增记录
*/
@ApiOperation("保存短信供应商表")
@ApiImplicitParams({
@ApiImplicitParam(name = "rowId", value = "唯一ID", paramType = "query"),
@ApiImplicitParam(name = "sortNo", value = "记录顺序", paramType = "query"),
@ApiImplicitParam(name = "createDt", value = "创建日期", paramType = "query"),
@ApiImplicitParam(name = "updateDt", value = "修改日期", paramType = "query"),
@ApiImplicitParam(name = "createUid", value = "创建人", paramType = "query"),
@ApiImplicitParam(name = "updateUid", value = "修改人", paramType = "query"),
@ApiImplicitParam(name = "dataFlg", value = "状态位", paramType = "query"),
@ApiImplicitParam(name = "objName", value = "备注", paramType = "query"),
@ApiImplicitParam(name = "masterRowId", value = "父表ID", paramType = "query"),
@ApiImplicitParam(name = "flowTransId", value = "事务ID", paramType = "query"),
@ApiImplicitParam(name = "flowStatus", value = "流程状态", paramType = "query"),
@ApiImplicitParam(name = "recordVersion", value = "乐观锁", paramType = "query"),
@ApiImplicitParam(name = "isDefault", value = "是否默认", paramType = "query"),
@ApiImplicitParam(name = "supName", value = "短信商名称", paramType = "query"),
@ApiImplicitParam(name = "recvMsgUrl", value = "接收消息URL", paramType = "query"),
@ApiImplicitParam(name = "queryBalanceUrl", value = "查询余额URL", paramType = "query"),
@ApiImplicitParam(name = "chgPassUrl", value = "修改密码URL", paramType = "query"),
@ApiImplicitParam(name = "sendMessUrl", value = "发送短信URL", paramType = "query"),
@ApiImplicitParam(name = "abbrName", value = "短信商简称", paramType = "query"),
@ApiImplicitParam(name = "interfaceAddr", value = "接口地址", paramType = "query"),
@ApiImplicitParam(name = "supCode", value = "短信商编码", paramType = "query"),
@ApiImplicitParam(name = "provinceId", value = "省份", paramType = "query"),
@ApiImplicitParam(name = "homePage", value = "主页", paramType = "query"),
@ApiImplicitParam(name = "registChildUrl", value = "注册子账号URL", paramType = "query"),
@ApiImplicitParam(name = "encodingType", value = "接口字符集", paramType = "query"),
@ApiImplicitParam(name = "filterWordsUrl", value = "敏感词URL", paramType = "query"),
@ApiImplicitParam(name = "recvSmsUrl", value = "收短信URL", paramType = "query"),
@ApiImplicitParam(name = "errorUrl", value = "错误信息URL", paramType = "query"),
})
@RequestMapping("/save")
public ResponseResult save( SmsSupplierParam param){
try {
log.info("新增记录调用开始..........");
this.smsSupplierService.save(param);
log.info("新增记录调用结束..........");
return ResponseResult.okResult(0,"新增成功!");
}
catch(Exception ex){
ex.printStackTrace();
return ResponseResult.errorResult(-1,"新增失败!");
}
}
/**
* 新增或修改记录
* @param param
* @return
*/
@RequestMapping("saveOrUpdate")
public ResponseResult saveOrUpdate( SmsSupplierParam param){
if(param==null){
return ResponseResult.errorResult(-1,"未传入参数.....");
}
try {
String rowId = param.getRowId();
log.info("根据rowId查询实体开始..........");
SmsSupplier ent = this.smsSupplierService.queryByRowId(param.getRowId());
if(ent!=null) {
//复制修改的参数
ent.setRowId(param.getRowId());
ent.setSortNo(param.getSortNo());
ent.setCreateDt(param.getCreateDt());
ent.setUpdateDt(param.getUpdateDt());
ent.setCreateUid(param.getCreateUid());
ent.setUpdateUid(param.getUpdateUid());
ent.setDataFlg(param.getDataFlg());
ent.setObjName(param.getObjName());
ent.setMasterRowId(param.getMasterRowId());
ent.setFlowTransId(param.getFlowTransId());
ent.setFlowStatus(param.getFlowStatus());
ent.setRecordVersion(param.getRecordVersion());
ent.setIsDefault(param.getIsDefault());
ent.setSupName(param.getSupName());
ent.setRecvMsgUrl(param.getRecvMsgUrl());
ent.setQueryBalanceUrl(param.getQueryBalanceUrl());
ent.setChgPassUrl(param.getChgPassUrl());
ent.setSendMessUrl(param.getSendMessUrl());
ent.setAbbrName(param.getAbbrName());
ent.setInterfaceAddr(param.getInterfaceAddr());
ent.setSupCode(param.getSupCode());
ent.setProvinceId(param.getProvinceId());
ent.setHomePage(param.getHomePage());
ent.setRegistChildUrl(param.getRegistChildUrl());
ent.setEncodingType(param.getEncodingType());
ent.setFilterWordsUrl(param.getFilterWordsUrl());
ent.setRecvSmsUrl(param.getRecvSmsUrl());
ent.setErrorUrl(param.getErrorUrl());
this.smsSupplierService.updateById(ent);
}
else{
log.info("没找到实体类..,新增...");
this.smsSupplierService.save(param);
}
log.info("保存完毕..........");
}
catch(Exception ex){
ex.printStackTrace();
return ResponseResult.errorResult(-1,"新增失败!");
}
return ResponseResult.okResult(0,"success");
}
/**
* 查询列表不分页
* @param param
* @return
*/
@RequestMapping("query")
public ResponseResult queryList(SmsSupplierParam param ){
List<SmsSupplier> list = null;
try{
list = this.smsSupplierService.queryList(param);
}
catch(Exception ex){
log.error("异常::::"+ex.toString());
return ResponseResult.errorResult(-1,ex.toString());
}
return ResponseResult.okResult(list);
}
/**
* 查询单条记录
* @param rowId
* @return
*/
@RequestMapping("edit")
public ResponseResult edit(String rowId){
SmsSupplier ent = this.smsSupplierService.queryByRowId(rowId);
return ResponseResult.okResult(ent);
}
/**
* 分页查询
* @param param
* @return
*/
@RequestMapping("findPage")
public ResponseResult findPage(SmsSupplierParam param){
IPage<SmsSupplier> page = this.smsSupplierService.findPage(param);
return ResponseResult.okResult(page);
}
}
API接口类源码支持Swagger接口注解。
五、接口测试
启动openjweb-sys的应用,访问http://localhost:8001/api/smsSupplier/query

访问测试链接,可以查到数据了,是不是很牛-X啊?
六、查看Swagger接口
访问http://localhost:8001/doc.html,因为目前在SpringSecurity中增加的允许doc.html不授权访问还没配好,所以需要访问http://localhost:8001/login登录一下,在前面介绍的使用admin,密码Hello0214@ 登录,然后再访问http://localhost:8001/doc.html:

展开供应商接口列表:

可以看到接口文档都生成出来了。
总结:
(1)到目前为止,我们完整实现了根据数据库表和Beetl代码模板生成源码的功能,以及生成Swagger开发文档,通过低代码的方式大大提高了开发效率。
(2)前端VUE页面的低代码生成还没开发,后面在适当的时候会开发前端VUE页面的自动生成。
(3)因为基于数据库元数据获取的信息有限,只能得到表和字段的注释,所以需要考虑使用自定义元数据管理表来实现更个性化的低代码生成。OpenJweb平台的comm_table_def和comm_column_def分别是表信息表和表字段信息表,表字段信息表不仅指定了表字段的名称、说明、字段类型,还指定了在HTML 页面中以什么形式呈现,这样我们可以先定义好每个字段的输入组件,然后利用定义好的字段信息来生成前端页面。
本节示例代码可从github上下载:
https://github.com/openjweb/cloud/tree/master
https://github.com/openjweb/cloud/tree/master
更多推荐



所有评论(0)