Develop small tools (entity class, return map, sql statement is automatically generated)

Create a project, import maven dependencies

1. Add Thymeleaf dependency

要想使用Thhymeleaf,首先要在pom.xml文件中单独添加Thymeleaf依赖。
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
  • The default path for SpringBoot to store template pages is src/main/resources/templates or src/main/view/templates. This is the same no matter what template language is used. Of course, the default path can be customized, but it is generally not recommended. In addition, the default page file extension of Thymeleaf is .html

2. View control class 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. Tool control class ToolController.java is used to return table entity data

@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 tool service custom database settings entity class attributes
Amount use BigDecimal to avoid losing precision, you can customize settings according to Oracle and MySQL field attributes

**
 * 工具服务
 * @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 script, of course the front end is indispensable.
Insert picture description here
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)
		});
	});
});

Import jquery itself, quote the script in code_ceate.html

6.code_create.html main interface

<!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" >&nbsp;&nbsp;数据表名称:
      	<input type="text" id="tableName" name="tableName" maxlength="50" class="_form"></input>&nbsp;<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. Visit url http://localhost:8064/views/code_create,
enter the table name and click OK to generate entity class attributes, xml returns map, and sql
Insert picture description here
can also be automatically generated in reverse using mybatis,

Guess you like

Origin blog.csdn.net/qq_38893133/article/details/103813088