创建工程、导入maven依赖
1.添加Thymeleaf依赖
要想使用Thhymeleaf,首先要在pom.xml文件中单独添加Thymeleaf依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- SpringBoot默认存放模板页面的路径在src/main/resources/templates或者src/main/view/templates,这个无论是使用什么模板语言都一样,当然默认路径是可以自定义的,不过一般不推荐这样做。另外Thymeleaf默认的页面文件后缀是.html
2.视图控制类 ViewsController.java
@Controller
@RequestMapping(value = "/views")
public class ViewsController {
@RequestMapping("/{view}")
public String toView(@PathVariable("view") String view) {
return String.format("%s", view);
}
@RequestMapping("{model}/{view}")
public String toView(@PathVariable("model") String model, @PathVariable("view") String view) {
return String.format("%s/%s", model, view);
}
@RequestMapping("{model}/{module}/{view}")
public String toSubView(@PathVariable("model") String model, @PathVariable("module") String module,
@PathVariable("view") String view) {
return String.format("%s/%s/%s", model, module, view);
}
@RequestMapping("{model}/{module}/{view}/{subview}")
public String toSubSubView(@PathVariable("model") String model, @PathVariable("module") String module,
@PathVariable("view") String view,@PathVariable("subview") String subview) {
return String.format("%s/%s/%s/%s", model, module, view,subview);
}
}
3.工具控制类 ToolController.java 用于返回table实体数据
@RestController
@RequestMapping("/tool")
public class ToolController extends BaseController{
//jdbc
@Resource
private ToolService toolService;
/**
* 获取表信息
* @param response
* @param tableName
* @throws Exception
*/
@RequestMapping("getTableInfo")
@ResponseBody
public BaseResult<?> getTableInfo(HttpServletResponse response, @RequestParam(defaultValue = "") String tableName) throws Exception {
List<Map<String,String>> tableInfoMap = toolService.getTableInfoList(tableName);
return ResultUtils.build(tableInfoMap);
}
}
4.ToolService.java 工具服务 自定义数据库设置实体类属性
金额使用BigDecimal避免丢失精度,可以根据Oracle和MySQL字段属性自定义设置
**
* 工具服务
* @author liucw
*
*/
@Service
public class ToolService {
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 通过表名获取表的信息
* @param tableName
* @return
* @throws Exception
*/
public List<Map<String,String>> getTableInfoList(String tableName) throws Exception {
String sql = "select * from "+tableName;
SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql);
SqlRowSetMetaData sqlRsmd = sqlRowSet.getMetaData();
List<Map<String,String>> tableFieldList = new ArrayList<Map<String,String>>();
int columnCount = sqlRsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
Map<String,String> fieldMap = new HashMap<String,String>();
String columnName = sqlRsmd.getColumnName(i);
String columnType = sqlRsmd.getColumnTypeName(i);
if(columnType.equalsIgnoreCase("NUMBER")||columnType.equalsIgnoreCase("INTEGER")||columnType.equalsIgnoreCase("INT")||columnType.equalsIgnoreCase("SMALLINT")||columnType.equalsIgnoreCase("TINYINT")) columnType="Integer";
else if(columnType.equalsIgnoreCase("VARCHAR")||columnType.equalsIgnoreCase("NCHAR")||columnType.equalsIgnoreCase("NVARCHAR2")||columnType.equalsIgnoreCase("VARCHAR2")|columnType.equalsIgnoreCase("CHAR")||columnType.equalsIgnoreCase("LONG VARCHAR")) columnType="String";
else if(columnType.equalsIgnoreCase("BIGINT"))columnType="Long";
/* else if(columnType.equalsIgnoreCase("DECIMAL"))columnType="Double";
else if(columnType.equalsIgnoreCase("FLOAT"))columnType="Float";*/
else if(columnType.equalsIgnoreCase("DECIMAL"))columnType="BigDecimal";
else if(columnType.equalsIgnoreCase("FLOAT"))columnType="BigDecimal";
else if(columnType.equalsIgnoreCase("TEXT"))columnType="String";
else if(columnType.equalsIgnoreCase("DATE"))columnType="Date";
else if(columnType.equalsIgnoreCase("DATETIME"))columnType="Date";
else if(columnType.equalsIgnoreCase("JSON"))columnType="JsonNode";
else if(columnType.equalsIgnoreCase("TIMESTAMP"))columnType="Timestamp";
else columnType="不支持类型";
fieldMap.put("columnName", columnName);
fieldMap.put("columnType", columnType);
tableFieldList.add(fieldMap);
}
return tableFieldList;
}
}
5.js脚本,前端当然少不了啦。
code_create.js
$(document).ready(function(){
$('#submitClick').click(function(){
var url = basePath + "tool/getTableInfo";
var param = {};
$('._form').each(function() {
var name = $(this).attr('id');
var value = $(this).val();
param[name] = value;
});
var tableName = $("#tableName").val();
$.post(url, param, function(returnedData, status) {
console.log(returnedData)
if ("success" == status) {
var columnList = returnedData.data;
var classCode = "";
var insertSql = "insert into " + tableName + "(";
var updateSql = "update "+tableName+" set ";
var sqlMap = "<resultMap id=\"\" type=\"\">\n";
var columns = "";
var props = "";
var updateValues = "";
var sqlMapResult = "";
for(var i=0;i<columnList.length;i++) {
columns = columns + "," + columnList[i].columnName;
var p = "private "+columnList[i].columnType + " ";
var columnName = columnList[i].columnName.toLowerCase();
var attrName_t = "";
if(columnName.indexOf("_")>=0) {
var attrNames = columnName.split("_");
for(var k=0;k<attrNames.length;k++) {
var at = attrNames[k];
if(k>0) {
at = attrNames[k].substring(0,1).toUpperCase() + attrNames[k].substring(1,attrNames[k].length); 转大写
}
attrName_t = attrName_t + at;
}
}
if(attrName_t != "") {
columnName=attrName_t;
}
props = props + ",#{" + columnName +"}";
sqlMapResult = sqlMapResult + "<result property=\""+columnName+"\" column=\""+columnList[i].columnName+"\"/>\n";
updateValues = updateValues + "," + columnList[i].columnName + "=#{"+columnName+"}";
classCode = classCode + p + " " + columnName +";//\n";
}
sqlMap = sqlMap + sqlMapResult + "</resultMap>";
$("#classCode").val(classCode);
$("#resultMap").val(sqlMap);
insertSql = insertSql + columns.replace(",","") + ") values(" + props.replace(",","") + ")";
updateSql = updateSql + updateValues.replace(",","") + "where ";
$("#sqlCode").val(insertSql+"\n\n\n\n"+updateSql);
} else {
console.log(returnedData);
console.log(returnedData)
}
}, "json").error(function(data,errorText,errorType){
//alert(data);
console.log(data)
});
});
});
jquery 自行导入,在code_ceate.html引用脚本
6.code_create.html 主界面
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
<script th:src="${#httpServletRequest.contextPath + '/static/scripts/jquery-1.11.1.js?r=2'}" type="text/javascript"></script>
<input name="basePath" id="basePath" type="hidden" th:value="${#httpServletRequest.scheme+'://'+#httpServletRequest.serverName+':'+#httpServletRequest.serverPort+#httpServletRequest.contextPath+'/'}"/>
<script type="text/javascript">
var basePath = $("#basePath").val();
//定义replaceAll方法
String.prototype.replaceAll = function(s1,s2){
return this.replace(new RegExp(s1,"gm"),s2);
};
</script>
<script th:src="${#httpServletRequest.contextPath + '/static/scripts/code_create.js?r=2'}" type="text/javascript"></script>
</head>
<body>
<div class="contBox m-l100 m-t30">
<form id="form1" name="form1" method="get" action="" onSubmit="javascript:return false;" autocomplete="off">
<div class="formBox formBox-add">
<table class="table_form_h" width="100%" border="0" cellpadding="1" cellspacing="1">
<tr>
<td width="50%" nowrap="nowrap" > 数据表名称:
<input type="text" id="tableName" name="tableName" maxlength="50" class="_form"></input> <font color="red">*</font>
<input type="button" value="确 定" class="button spmg-right" id="submitClick" />
</td>
</tr>
<tr>
<td>
<textarea id="classCode" rows="30" cols="30"></textarea>
<textarea id="resultMap" rows="30" cols="50"></textarea>
<textarea id="sqlCode" rows="30" cols="90"></textarea>
</td>
</tr>
</table>
</div>
</form>
</div>
</body>
</html>
7.访问url http://localhost:8064/views/code_create
输入表名称 点击确定 生成实体类属性,xml返回map ,以及sql
也可以使用mybatis 逆向自动生成 ,