支持联表查询

This commit is contained in:
keyleaf 2021-05-25 15:44:37 +08:00
parent b5110d2062
commit 9c74df5d37
11 changed files with 495 additions and 26 deletions

View File

@ -2,7 +2,7 @@ package com.ruoyi.common.constant;
/** /**
* 代码生成通用常量 * 代码生成通用常量
* *
* @author ruoyi * @author ruoyi
*/ */
public class GenConstants public class GenConstants
@ -16,6 +16,9 @@ public class GenConstants
/** 主子表(增删改查) */ /** 主子表(增删改查) */
public static final String TPL_SUB = "sub"; public static final String TPL_SUB = "sub";
/** 关联表(增删改查) */
public static final String TPL_JOIN = "join";
/** 树编码字段 */ /** 树编码字段 */
public static final String TREE_CODE = "treeCode"; public static final String TREE_CODE = "treeCode";

View File

@ -1,7 +1,10 @@
package com.ruoyi.generator.domain; package com.ruoyi.generator.domain;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.*; import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.constant.GenConstants;
import lombok.*; import lombok.*;
@ -11,10 +14,7 @@ import org.apache.commons.lang3.ArrayUtils;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* 业务表 gen_table * 业务表 gen_table
@ -114,6 +114,18 @@ public class GenTable implements Serializable {
@TableField(exist = false) @TableField(exist = false)
private GenTableColumn pkColumn; private GenTableColumn pkColumn;
/**
* 关联表配置信息
*/
@TableField(typeHandler = JacksonTypeHandler.class)
private List<JoinInfo> joinInfos;
/**
* 关联表信息
*/
@TableField(exist = false)
private Map<String, GenTable> joinTableMap = new HashMap<>();
/** /**
* 子表信息 * 子表信息
*/ */
@ -234,4 +246,57 @@ public class GenTable implements Serializable {
} }
return StrUtil.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY); return StrUtil.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY);
} }
}
/**
* 关联表信息
*
* 举例
* select A.xxx, B.xxx(showFields) from A left join B(joinTable) on A.fk_id(tableFkName) = B.id(joinField)
*/
@Data
public static class JoinInfo {
/**
* 关联表的名称
*/
private String joinTable;
/**
* 主表的关联字段
*/
private String tableFkName;
/**
* 关联表的关联字段
*/
private String joinField;
/**
* 关联表中要展示的字段
*/
private LinkedHashSet<String> showFields;
/**
* 查询列表要展示的字段
*/
private LinkedHashSet<String> queryFields;
}
/**
* 自定义类型转换器
* 服务于GenTableMapper.xml
*/
public static class JoinInfoTypeHandler extends AbstractJsonTypeHandler<List<JoinInfo>> {
@Override
protected List<JoinInfo> parse(String json) {
return JSON.parseArray(json, JoinInfo.class);
}
@Override
protected String toJson(List<JoinInfo> obj) {
return JSON.toJSONString(obj);
}
}
}

View File

@ -24,12 +24,14 @@ import com.ruoyi.generator.util.VelocityInitializer;
import com.ruoyi.generator.util.VelocityUtils; import com.ruoyi.generator.util.VelocityUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template; import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity; import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
@ -203,6 +205,8 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
GenTable table = baseMapper.selectGenTableById(tableId); GenTable table = baseMapper.selectGenTableById(tableId);
// 设置主子表信息 // 设置主子表信息
setSubTable(table); setSubTable(table);
// 设置关联表信息
setJoinTable(table);
// 设置主键列信息 // 设置主键列信息
setPkColumn(table); setPkColumn(table);
VelocityInitializer.initVelocity(); VelocityInitializer.initVelocity();
@ -247,6 +251,8 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
GenTable table = baseMapper.selectGenTableByName(tableName); GenTable table = baseMapper.selectGenTableByName(tableName);
// 设置主子表信息 // 设置主子表信息
setSubTable(table); setSubTable(table);
// 设置关联表信息
setJoinTable(table);
// 设置主键列信息 // 设置主键列信息
setPkColumn(table); setPkColumn(table);
@ -329,6 +335,8 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
GenTable table = baseMapper.selectGenTableByName(tableName); GenTable table = baseMapper.selectGenTableByName(tableName);
// 设置主子表信息 // 设置主子表信息
setSubTable(table); setSubTable(table);
// 设置关联表信息
setJoinTable(table);
// 设置主键列信息 // 设置主键列信息
setPkColumn(table); setPkColumn(table);
@ -378,7 +386,11 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
} else if (Validator.isEmpty(genTable.getSubTableFkName())) { } else if (Validator.isEmpty(genTable.getSubTableFkName())) {
throw new CustomException("子表关联的外键名不能为空"); throw new CustomException("子表关联的外键名不能为空");
} }
} } else if (GenConstants.TPL_JOIN.equals(genTable.getTplCategory())) {
if (CollectionUtils.isEmpty(genTable.getJoinInfos())) {
throw new CustomException("关联表的相关配置不能为空");
}
}
} }
} }
@ -422,6 +434,25 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
} }
} }
/**
* 设置关联表的信息
* @param table
*/
public void setJoinTable(GenTable table) {
Map<String, GenTable> joinTableMap = table.getJoinTableMap();
List<GenTable.JoinInfo> joinInfos = table.getJoinInfos();
if (!CollectionUtils.isEmpty(joinInfos)) {
for (GenTable.JoinInfo joinInfo: joinInfos) {
String joinTable = joinInfo.getJoinTable();
if (StringUtils.isNotBlank(joinTable)) {
GenTable joinGenTable = baseMapper.selectGenTableByName(joinTable);
setPkColumn(joinGenTable);
joinTableMap.put(joinTable, joinGenTable);
}
}
}
}
/** /**
* 设置代码生成其他选项值 * 设置代码生成其他选项值
* *
@ -458,4 +489,4 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
} }
return genPath + File.separator + VelocityUtils.getFileName(template, table); return genPath + File.separator + VelocityUtils.getFileName(template, table);
} }
} }

View File

@ -1,5 +1,6 @@
package com.ruoyi.generator.util; package com.ruoyi.generator.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator; import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
@ -7,15 +8,15 @@ import com.ruoyi.common.constant.GenConstants;
import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn; import com.ruoyi.generator.domain.GenTableColumn;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList; import java.util.*;
import java.util.HashSet;
import java.util.List;
/** /**
* 模板处理工具类 * 模板处理工具类
* *
* @author ruoyi * @author ruoyi
*/ */
public class VelocityUtils public class VelocityUtils
@ -69,6 +70,10 @@ public class VelocityUtils
{ {
setSubVelocityContext(velocityContext, genTable); setSubVelocityContext(velocityContext, genTable);
} }
if (GenConstants.TPL_JOIN.equals(tplCategory))
{
setJoinVelocityContext(velocityContext, genTable);
}
return velocityContext; return velocityContext;
} }
@ -120,6 +125,101 @@ public class VelocityUtils
context.put("subImportList", getImportList(genTable.getSubTable())); context.put("subImportList", getImportList(genTable.getSubTable()));
} }
/**
* 关联表类型的相关参数封装
* @param context
* @param genTable
*/
public static void setJoinVelocityContext(VelocityContext context, GenTable genTable) {
List<GenTable.JoinInfo> joinInfos = genTable.getJoinInfos();
Map<String, GenTable> joinTableMap = genTable.getJoinTableMap();
List<GenTableColumn> genTableColumns = genTable.getColumns();
Map<String, GenTableColumn> genTableColumnMap = CollUtil.fieldValueMap(genTableColumns, "columnName");
List<Map<String, Object>> joinInfoList = new ArrayList<>();
context.put("joinInfos", joinInfoList);
if (!CollectionUtils.isEmpty(joinInfos)) {
for (GenTable.JoinInfo joinInfo : joinInfos) {
Map<String, Object> joinInfoMap = new HashMap<>();
joinInfoList.add(joinInfoMap);
String joinTable = joinInfo.getJoinTable();
String joinTableClassName = StrUtil.toCamelCase(joinTable);
String joinTableLowerClassName = StrUtil.lowerFirst(joinTableClassName);
String joinTableUpperClassName = StrUtil.upperFirst(joinTableClassName);
joinInfoMap.put("joinGenTable", joinTableMap.get(joinTable));
joinInfoMap.put("joinGenTableBusinessName", StrUtil.upperFirst(joinTableMap.get(joinTable).getBusinessName()));
joinInfoMap.put("joinGenTableModuleName", StrUtil.upperFirst(joinTableMap.get(joinTable).getModuleName()));
joinInfoMap.put("joinTable", joinTable);
joinInfoMap.put("joinTableClassName", joinTableClassName);
joinInfoMap.put("joinTableLowerClassName", joinTableLowerClassName);
joinInfoMap.put("joinTableUpperClassName", joinTableUpperClassName);
String tableFkName = joinInfo.getTableFkName();
joinInfoMap.put("tableFkName", tableFkName);
GenTableColumn genTableColumn = genTableColumnMap.get(tableFkName);
// 主表关联的字段(tableFkName)如果本身就在列表中展示就会在各个vm中生成拼接如果不需要在列表中展示关联查询却仍需要这个字段为避免重复生成增加该flag进行判断
joinInfoMap.put("tableFkGenerateFlag", !genTableColumn.isList());
joinInfoMap.put("tableFkColumn", genTableColumn);
String joinField = joinInfo.getJoinField();
joinInfoMap.put("joinField", joinField);
LinkedHashSet<String> showFields = joinInfo.getShowFields();
List<Map<String, String>> showFieldList = new ArrayList<>();
joinInfoMap.put("showFields", showFieldList);
if (!CollectionUtils.isEmpty(showFields)) {
GenTable joinGenTable = joinTableMap.get(joinTable);
List<GenTableColumn> columns = joinGenTable.getColumns();
Map<String, GenTableColumn> columnMap = CollUtil.fieldValueMap(columns, "columnName");
for (String showField : showFields) {
Map<String, String> showFieldMap = new HashMap<>();
showFieldList.add(showFieldMap);
String showFiledName = StrUtil.toCamelCase(showField);
String showFiledUpperName = StrUtil.upperFirst(showFiledName);
showFieldMap.put("showField", showField);
showFieldMap.put("showFiledName", showFiledName);
showFieldMap.put("showFiledUpperName", showFiledUpperName);
GenTableColumn column = columnMap.get(showField);
showFieldMap.put("showFieldJavaType", column.getJavaType());
showFieldMap.put("showFieldDictType", column.getDictType());
if (StringUtils.isNotBlank(column.getColumnComment())) {
showFieldMap.put("showFieldComment", column.getColumnComment());
} else {
showFieldMap.put("showFieldComment", joinTableLowerClassName + showFiledUpperName);
}
}
}
LinkedHashSet<String> queryFields = joinInfo.getQueryFields();
List<Map<String, String>> queryFieldList = new ArrayList<>();
joinInfoMap.put("queryFields", queryFieldList);
if (!CollectionUtils.isEmpty(queryFields)) {
GenTable joinGenTable = joinTableMap.get(joinTable);
List<GenTableColumn> columns = joinGenTable.getColumns();
Map<String, GenTableColumn> columnMap = CollUtil.fieldValueMap(columns, "columnName");
for (String queryField : queryFields) {
Map<String, String> queryFieldMap = new HashMap<>();
queryFieldList.add(queryFieldMap);
String queryFiledName = StrUtil.toCamelCase(queryField);
String queryFiledUpperName = StrUtil.upperFirst(queryFiledName);
queryFieldMap.put("queryField", queryField);
queryFieldMap.put("queryFiledName", queryFiledName);
queryFieldMap.put("queryFiledUpperName", queryFiledUpperName);
GenTableColumn column = columnMap.get(queryField);
if (StringUtils.isNotBlank(column.getColumnComment())) {
queryFieldMap.put("queryFieldComment", column.getColumnComment());
} else {
queryFieldMap.put("queryFieldComment", joinTableLowerClassName + queryFiledUpperName);
}
}
}
}
}
}
/** /**
* 获取模板信息 * 获取模板信息
* *
@ -140,7 +240,7 @@ public class VelocityUtils
templates.add("vm/xml/mapper.xml.vm"); templates.add("vm/xml/mapper.xml.vm");
templates.add("vm/sql/sql.vm"); templates.add("vm/sql/sql.vm");
templates.add("vm/js/api.js.vm"); templates.add("vm/js/api.js.vm");
if (GenConstants.TPL_CRUD.equals(tplCategory)) if (GenConstants.TPL_CRUD.equals(tplCategory) || GenConstants.TPL_JOIN.equals(tplCategory))
{ {
templates.add("vm/vue/index.vue.vm"); templates.add("vm/vue/index.vue.vm");
} }

View File

@ -10,6 +10,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="tableComment" column="table_comment" /> <result property="tableComment" column="table_comment" />
<result property="subTableName" column="sub_table_name" /> <result property="subTableName" column="sub_table_name" />
<result property="subTableFkName" column="sub_table_fk_name" /> <result property="subTableFkName" column="sub_table_fk_name" />
<result property="joinInfos" column="join_infos" typeHandler="com.ruoyi.generator.domain.GenTable$JoinInfoTypeHandler" javaType="java.util.List" />
<result property="className" column="class_name" /> <result property="className" column="class_name" />
<result property="tplCategory" column="tpl_category" /> <result property="tplCategory" column="tpl_category" />
<result property="packageName" column="package_name" /> <result property="packageName" column="package_name" />
@ -27,7 +28,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="remark" column="remark" /> <result property="remark" column="remark" />
<collection property="columns" javaType="java.util.List" resultMap="GenTableColumnResult" /> <collection property="columns" javaType="java.util.List" resultMap="GenTableColumnResult" />
</resultMap> </resultMap>
<resultMap type="GenTableColumn" id="GenTableColumnResult"> <resultMap type="GenTableColumn" id="GenTableColumnResult">
<id property="columnId" column="column_id" /> <id property="columnId" column="column_id" />
<result property="tableId" column="table_id" /> <result property="tableId" column="table_id" />
@ -52,7 +53,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="updateBy" column="update_by" /> <result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" /> <result property="updateTime" column="update_time" />
</resultMap> </resultMap>
<sql id="selectGenTableVo"> <sql id="selectGenTableVo">
select table_id, table_name, table_comment, sub_table_name, sub_table_fk_name, class_name, tpl_category, package_name, module_name, business_name, function_name, function_author, gen_type, gen_path, options, create_by, create_time, update_by, update_time, remark from gen_table select table_id, table_name, table_comment, sub_table_name, sub_table_fk_name, class_name, tpl_category, package_name, module_name, business_name, function_name, function_author, gen_type, gen_path, options, create_by, create_time, update_by, update_time, remark from gen_table
</sql> </sql>
@ -131,32 +132,32 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
AND date_format(create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d') AND date_format(create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if> </if>
</select> </select>
<select id="selectDbTableListByNames" resultMap="GenTableResult"> <select id="selectDbTableListByNames" resultMap="GenTableResult">
select table_name, table_comment, create_time, update_time from information_schema.tables select table_name, table_comment, create_time, update_time from information_schema.tables
where table_name NOT LIKE 'qrtz_%' and table_name NOT LIKE 'gen_%' and table_schema = (select database()) where table_name NOT LIKE 'qrtz_%' and table_name NOT LIKE 'gen_%' and table_schema = (select database())
and table_name in and table_name in
<foreach collection="array" item="name" open="(" separator="," close=")"> <foreach collection="array" item="name" open="(" separator="," close=")">
#{name} #{name}
</foreach> </foreach>
</select> </select>
<select id="selectTableByName" parameterType="String" resultMap="GenTableResult"> <select id="selectTableByName" parameterType="String" resultMap="GenTableResult">
select table_name, table_comment, create_time, update_time from information_schema.tables select table_name, table_comment, create_time, update_time from information_schema.tables
where table_comment <![CDATA[ <> ]]> '' and table_schema = (select database()) where table_comment <![CDATA[ <> ]]> '' and table_schema = (select database())
and table_name = #{tableName} and table_name = #{tableName}
</select> </select>
<select id="selectGenTableById" parameterType="Long" resultMap="GenTableResult"> <select id="selectGenTableById" parameterType="Long" resultMap="GenTableResult">
SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark, SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.join_infos, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
FROM gen_table t FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id LEFT JOIN gen_table_column c ON t.table_id = c.table_id
where t.table_id = #{tableId} order by c.sort where t.table_id = #{tableId} order by c.sort
</select> </select>
<select id="selectGenTableByName" parameterType="String" resultMap="GenTableResult"> <select id="selectGenTableByName" parameterType="String" resultMap="GenTableResult">
SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark, SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.join_infos, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
FROM gen_table t FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id LEFT JOIN gen_table_column c ON t.table_id = c.table_id
@ -171,4 +172,4 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
order by c.sort order by c.sort
</select> </select>
</mapper> </mapper>

View File

@ -49,4 +49,22 @@ public class ${ClassName}Vo {
#end #end
#end #end
#foreach ($joinInfo in $joinInfos)
#if(${joinInfo.tableFkGenerateFlag})
// 补充主表字段
private ${joinInfo.tableFkColumn.javaType} ${joinInfo.tableFkColumn.javaField};
#end
// 关联表 ${joinInfo.joinTableLowerClassName} 字段
#foreach ($showField in $joinInfo.showFields)
#if($showField.showFieldJavaType == 'Date')
@Excel(name = "${showField.showFieldComment}" , width = 30, dateFormat = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
#else
@Excel(name = "${showField.showFieldComment}")
#end
private ${showField.showFieldJavaType} ${joinInfo.joinTableLowerClassName}${showField.showFiledUpperName};
#end
#end
} }

View File

@ -138,6 +138,16 @@
#elseif($column.list && "" != $javaField) #elseif($column.list && "" != $javaField)
<el-table-column label="${comment}" align="center" prop="${javaField}" /> <el-table-column label="${comment}" align="center" prop="${javaField}" />
#end #end
#end
#foreach($joinInfo in $joinInfos)
<!-- 关联表 ${joinInfo.joinTableLowerClassName} 字段 -->
#foreach ($showField in $joinInfo.showFields)
#if($showField.showFieldDictType && "" != $showField.showFieldDictType)
<el-table-column label="${showField.showFieldComment}" align="center" prop="${joinInfo.joinTableLowerClassName}${showField.showFiledUpperName}" :formatter="${joinInfo.joinTableLowerClassName}${showField.showFiledUpperName}Format" />
#else
<el-table-column label="${showField.showFieldComment}" align="center" prop="${joinInfo.joinTableLowerClassName}${showField.showFiledUpperName}" />
#end
#end
#end #end
<el-table-column label="操作" align="center" class-name="small-padding fixed-width"> <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope"> <template slot-scope="scope">
@ -158,7 +168,7 @@
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
<pagination <pagination
v-show="total>0" v-show="total>0"
:total="total" :total="total"
@ -170,6 +180,29 @@
<!-- 添加或修改${functionName}对话框 --> <!-- 添加或修改${functionName}对话框 -->
<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body> <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="80px"> <el-form ref="form" :model="form" :rules="rules" label-width="80px">
#foreach($joinInfo in $joinInfos)
<el-form-item label="${joinInfo.tableFkColumn.columnComment}" prop="${joinInfo.tableFkColumn.javaField}">
<el-select
v-model="form.${joinInfo.tableFkColumn.javaField}"
filterable
remote
reserve-keyword
placeholder="请输入${joinInfo.showFields.get(0).showFieldComment}搜索"
:remote-method="remoteFetch${joinInfo.joinTableUpperClassName}"
value-key="${joinInfo.joinGenTable.pkColumn.javaField}"
>
<el-option
v-for="item in ${joinInfo.joinTableLowerClassName}Options"
:key="item.${joinInfo.joinGenTable.pkColumn.javaField}"
:label="item.${joinInfo.showFields.get(0).showFiledName}"
:value="item.${joinInfo.joinGenTable.pkColumn.javaField}"
/>
</el-select>
</el-form-item>
#end
#foreach($column in $columns) #foreach($column in $columns)
#set($field=$column.javaField) #set($field=$column.javaField)
#if($column.insert && !$column.pk) #if($column.insert && !$column.pk)
@ -309,6 +342,10 @@
<script> <script>
import { list${BusinessName}, get${BusinessName}, del${BusinessName}, add${BusinessName}, update${BusinessName}, export${BusinessName} } from "@/api/${moduleName}/${businessName}"; import { list${BusinessName}, get${BusinessName}, del${BusinessName}, add${BusinessName}, update${BusinessName}, export${BusinessName} } from "@/api/${moduleName}/${businessName}";
#foreach($joinInfo in $joinInfos)
import { list${joinInfo.joinGenTableBusinessName} } from "@/api/${joinInfo.joinGenTable.moduleName}/${joinInfo.joinGenTable.businessName}";
#end
#foreach($column in $columns) #foreach($column in $columns)
#if($column.insert && !$column.superColumn && !$column.pk && $column.htmlType == "imageUpload") #if($column.insert && !$column.superColumn && !$column.pk && $column.htmlType == "imageUpload")
import ImageUpload from '@/components/ImageUpload'; import ImageUpload from '@/components/ImageUpload';
@ -370,6 +407,9 @@ export default {
total: 0, total: 0,
// ${functionName}表格数据 // ${functionName}表格数据
${businessName}List: [], ${businessName}List: [],
#foreach($joinInfo in $joinInfos)
${joinInfo.joinGenTable.moduleName}${joinInfo.joinGenTableBusinessName}Options: [],
#end
#if($table.sub) #if($table.sub)
// ${subTable.functionName}表格数据 // ${subTable.functionName}表格数据
${subclassName}List: [], ${subclassName}List: [],
@ -393,6 +433,14 @@ export default {
// $comment时间范围 // $comment时间范围
daterange${AttrName}: [], daterange${AttrName}: [],
#end #end
#end
#foreach($joinInfo in $joinInfos)
#foreach ($showField in $joinInfo.showFields)
#if($showField.showFieldDictType && "" != $showField.showFieldDictType)
// $comment字典
${joinInfo.joinTableLowerClassName}${showField.showFiledUpperName}Options: [],
#end
#end
#end #end
// 查询参数 // 查询参数
queryParams: { queryParams: {
@ -434,6 +482,16 @@ export default {
this.${column.javaField}Options = response.data; this.${column.javaField}Options = response.data;
}); });
#end #end
#end
#foreach($joinInfo in $joinInfos)
#foreach ($showField in $joinInfo.showFields)
#if($showField.showFieldDictType && "" != $showField.showFieldDictType)
this.getDicts("${showField.showFieldDictType}").then(response => {
this.${joinInfo.joinTableLowerClassName}${showField.showFiledUpperName}Options = response.data;
});
#end
#end
#end #end
}, },
methods: { methods: {
@ -461,6 +519,18 @@ export default {
this.loading = false; this.loading = false;
}); });
}, },
#foreach($joinInfo in $joinInfos)
remoteFetch${joinInfo.joinGenTableModuleName}${joinInfo.joinGenTableBusinessName}(keyword) {
let that = this;
list${joinInfo.joinGenTableBusinessName}({
pageNum: 1,
pageSize: 10,
${joinInfo.showFields.get(0).showFiledName}: keyword
}).then(response => {
that.${joinInfo.joinGenTable.moduleName}${joinInfo.joinGenTableBusinessName}Options = response.rows
});
},
#end
#foreach ($column in $columns) #foreach ($column in $columns)
#if(${column.dictType} != '') #if(${column.dictType} != '')
#set($parentheseIndex=$column.columnComment.indexOf("")) #set($parentheseIndex=$column.columnComment.indexOf(""))
@ -474,6 +544,16 @@ export default {
return this.selectDictLabel#if($column.htmlType == "checkbox")s#end(this.${column.javaField}Options, row.${column.javaField}); return this.selectDictLabel#if($column.htmlType == "checkbox")s#end(this.${column.javaField}Options, row.${column.javaField});
}, },
#end #end
#end
#foreach($joinInfo in $joinInfos)
#foreach ($showField in $joinInfo.showFields)
#if($showField.showFieldDictType && "" != $showField.showFieldDictType)
// $comment字典翻译
${joinInfo.joinTableLowerClassName}${showField.showFiledUpperName}Format(row, column) {
return this.selectDictLabel#if($column.htmlType == "checkbox")s#end(this.${joinInfo.joinTableLowerClassName}${showField.showFiledUpperName}Options, row.${joinInfo.joinTableLowerClassName}${showField.showFiledUpperName});
},
#end
#end
#end #end
// 取消按钮 // 取消按钮
cancel() { cancel() {

View File

@ -10,5 +10,55 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
#end #end
</resultMap> </resultMap>
#if($joinInfos)
<resultMap type="Map" id="JoinResult" extends="${ClassName}Result">
#foreach ($joinInfo in $joinInfos)
<!-- ${joinInfo.joinTableLowerClassName} -->
#foreach ($showField in $joinInfo.showFields)
<result property="${joinInfo.joinTableLowerClassName}${showField.showFiledUpperName}" column="${joinInfo.joinTable}_${showField.showField}"/>
#end
#end
</resultMap>
</mapper> <sql id="Base_Column_List">
select
<!-- 主表 ${tableName} 字段 -->
#foreach ($column in $columns)
${tableName}.${column.columnName} as ${column.columnName},
#end
#foreach ($joinInfo in $joinInfos)
<!-- 关联表 ${joinInfo.joinTableLowerClassName} 字段 -->
#foreach ($showField in $joinInfo.showFields)
${joinInfo.joinTable}.${showField.showField} as ${joinInfo.joinTable}_${showField.showField},
#end
#end
<!-- 最后的逗号没找到好办法去除,先手动去除 -->
from ${tableName}
#foreach ($joinInfo in $joinInfos)
left join ${joinInfo.joinTable} on ${tableName}.${joinInfo.tableFkName} = ${joinInfo.joinTable}.${joinInfo.joinField}
#end
</sql>
<select id="selectById" parameterType="Long" resultMap="JoinResult">
<include refid="Base_Column_List"></include>
where ${tableName}.${pkColumn.columnName} = #{id}
</select>
<select id="selectList" parameterType="Long" resultMap="JoinResult">
<include refid="Base_Column_List"></include>
<if test="ew.emptyOfWhere == false">
${ew.customSqlSegment}
</if>
</select>
<select id="selectPage" parameterType="Long" resultMap="JoinResult">
<include refid="Base_Column_List"></include>
<if test="ew.emptyOfWhere == false">
${ew.customSqlSegment}
</if>
</select>
#end
</mapper>

View File

@ -113,7 +113,7 @@
</el-table> </el-table>
</el-tab-pane> </el-tab-pane>
<el-tab-pane label="生成信息" name="genInfo"> <el-tab-pane label="生成信息" name="genInfo">
<gen-info-form ref="genInfo" :info="info" :tables="tables" :menus="menus"/> <gen-info-form ref="genInfo" :info="info" :tables="tables" :menus="menus" :columns="columns"/>
</el-tab-pane> </el-tab-pane>
</el-tabs> </el-tabs>
<el-form label-width="100px"> <el-form label-width="100px">

View File

@ -8,6 +8,7 @@
<el-option label="单表(增删改查)" value="crud" /> <el-option label="单表(增删改查)" value="crud" />
<el-option label="树表(增删改查)" value="tree" /> <el-option label="树表(增删改查)" value="tree" />
<el-option label="主子表(增删改查)" value="sub" /> <el-option label="主子表(增删改查)" value="sub" />
<el-option label="关联表(增删改查)" value="join" />
</el-select> </el-select>
</el-form-item> </el-form-item>
</el-col> </el-col>
@ -211,6 +212,101 @@
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-row> </el-row>
<el-row v-show="info.tplCategory == 'join'">
<h4 class="form-header">关联查询</h4>
<el-button type="primary" icon="el-icon-plus" size="mini" @click="addJoinInfo">新增</el-button>
<el-tooltip :content="info.tableName + ' left join 关联表 on 主表关联字段 = 子表关联字段'" placement="top">
<i class="el-icon-question"></i>
</el-tooltip>
<el-table :data="info.joinInfos" style="width: 100%">
<el-table-column
label="关联表名称"
>
<template slot-scope="scope">
<el-select v-model="scope.row.joinTable" placeholder="请选择" @change="scope.row.joinField = null; scope.row.showFields = []">
<el-option
v-for="(table, index) in tables"
:key="index"
:label="table.tableName + '' + table.tableComment"
:value="table.tableName"
></el-option>
</el-select>
</template>
</el-table-column>
<el-table-column
:label="'主表' + info.tableName + '的关联字段'"
>
<template slot-scope="scope">
<el-select v-model="scope.row.tableFkName" placeholder="请选择">
<el-option
v-for="(column, index) in columns"
:key="index"
:label="column.columnName + '' + column.columnComment"
:value="column.columnName"
></el-option>
</el-select>
</template>
</el-table-column>
<el-table-column
:label="'子表关联的字段'"
>
<template slot-scope="scope">
<el-select v-model="scope.row.joinField" placeholder="请选择">
<el-option
v-for="(column, index) in (tableMap.get(scope.row.joinTable) ? tableMap.get(scope.row.joinTable).columns : [])"
:key="index"
:label="column.columnName + '' + column.columnComment"
:value="column.columnName"
></el-option>
</el-select>
</template>
</el-table-column>
<el-table-column
label="子表展示字段"
min-width="100"
>
<template slot-scope="scope">
<el-select v-model="scope.row.showFields" multiple placeholder="请选择" style="width:100%">
<el-option
v-for="(column, index) in (tableMap.get(scope.row.joinTable) ? tableMap.get(scope.row.joinTable).columns : [])"
:key="index"
:label="column.columnName + '' + column.columnComment"
:value="column.columnName"
></el-option>
</el-select>
</template>
</el-table-column>
<el-table-column
label="列表查询条件(尚未完成)"
min-width="100"
>
<template slot-scope="scope">
<el-select v-model="scope.row.queryFields" multiple placeholder="请选择" style="width:100%">
<el-option
v-for="(column, index) in (tableMap.get(scope.row.joinTable) ? tableMap.get(scope.row.joinTable).columns : [])"
:key="index"
:label="column.columnName + '' + column.columnComment"
:value="column.columnName"
></el-option>
</el-select>
</template>
</el-table-column>
<el-table-column
:label="'操作'"
>
<template slot-scope="scope">
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="info.joinInfos.splice(scope.$index, 1)"
>删除</el-button>
</template>
</el-table-column>
</el-table>
</el-row>
</el-form> </el-form>
</template> </template>
<script> <script>
@ -233,10 +329,15 @@ export default {
type: Array, type: Array,
default: [] default: []
}, },
columns: {
type: Array,
default: []
},
}, },
data() { data() {
return { return {
subColumns: [], subColumns: [],
tableMap: new Map(), //
rules: { rules: {
tplCategory: [ tplCategory: [
{ required: true, message: "请选择生成模板", trigger: "blur" } { required: true, message: "请选择生成模板", trigger: "blur" }
@ -260,6 +361,13 @@ export default {
watch: { watch: {
'info.subTableName': function(val) { 'info.subTableName': function(val) {
this.setSubTableColumns(val); this.setSubTableColumns(val);
},
'tables': function(tables) {
const that = this
tables.forEach(table => {
that.tableMap.set(table.tableName, table)
console.log("tableMap is:", that.tableMap)
})
} }
}, },
methods: { methods: {
@ -284,9 +392,13 @@ export default {
this.info.subTableName = ''; this.info.subTableName = '';
this.info.subTableFkName = ''; this.info.subTableFkName = '';
} }
if(value !== 'join') {
this.info.joinInfos.splice(0, this.info.joinInfos.length);
}
}, },
/** 设置关联外键 */ /** 设置关联外键 */
setSubTableColumns(value) { setSubTableColumns(value) {
console.log(this.tables)
for (var item in this.tables) { for (var item in this.tables) {
const name = this.tables[item].tableName; const name = this.tables[item].tableName;
if (value === name) { if (value === name) {
@ -294,6 +406,14 @@ export default {
break; break;
} }
} }
},
addJoinInfo() {
this.info.joinInfos.push({
joinTable: null,
tableFkName: null,
joinField: null,
showFields: []
});
} }
} }
}; };

1
sql/ry_20210523.sql Normal file
View File

@ -0,0 +1 @@
alter table gen_table add join_infos json null comment '关联查询信息' after sub_table_fk_name;