欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

groovy 生成实体类

程序员文章站 2022-06-14 23:13:41
...

项目需要,写了一个生成类,有需要的可以看着改下.

import java.util.regex.Matcher
import java.util.regex.Pattern
import groovy.sql.Sql

class _genGenTable {

	//需要改动的参数 
	def JDBCNAME = "jdbc:mysql://xxxxx:13306/xxx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8&nullNamePatternMatchesAll=true&nullNamePatternMatchesAll=true";
	def USERNAME ="root";
	def PASSWORD ='xxx';
	def DIR = "src/main/java/com/xxx/entity/";
	
	
	def TABLE_SCHEMA = "xxxxxx";
	public static void main(String[] args) {
		new _genGenTable()._generateDataBase();
	}

	def _generateDataBase(){
		def fields = [];
		def mySql = _getMySql();
		mySql.eachRow(ALLTABLESQL){
			def typeStr = typeMapping.find {p, t -> p.matcher(it.data_type).find() }.value;
			fields += [[
					name : it.column_name,
					table_name: _getLumpName(it.table_name),
					real_table_name: it.table_name,
					real_data_type: it.data_type,
					extra: it.extra,
					type    : typeStr,
					comment : it.column_comment,
					column_key:it.column_key
				]];
		}
		mySql.close();
		if(fields.empty){
			println("没有对应的表");
			return;
		}
		new File(DIR).deleteDir();
		new File(DIR).mkdir();
		def map = _getTableMap(fields);
		for(m in map){
			new File(DIR, "${m.key}.java").withPrintWriter { out ->
				_generate(out, m.key,m.value);
			}
		}
		println("创建完毕:"+map.size());
		return true;
	}
	def _getMySql(){
		def mySql= Sql.newInstance(JDBCNAME,USERNAME,PASSWORD,"com.mysql.jdbc.Driver");
		return mySql;
	}
	def _getTableMap(fields){
		Map map = new HashMap();
		fields.each() {
			def table_fields = map.get(it.table_name);
			if(table_fields==null){
				table_fields = new ArrayList();
			}
			table_fields.add(it);
			map.put(it.table_name, table_fields);
		}
		return map;
	}

	def _getLumpName(name){
		//包名驼峰
		name = name.toLowerCase();
		Pattern linePattern = Pattern.compile("_(\\w)");
		Matcher matcher = linePattern.matcher(name);
		StringBuffer sb = new StringBuffer();
		while(matcher.find()){
			matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
		}
		matcher.appendTail(sb);
		return sb.toString().substring(0, 1).toUpperCase()+sb.toString().substring(1, sb.toString().length());
	}
	def _getPackageName(isF) {
		def packageName = DIR.toString().replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "");
		if(isF==1){
			return packageName.substring(0, packageName.length()-1)+ ";";
		}
		return packageName.substring(0, packageName.length()-1);
	}
	def _getBasePackageName(isF) {
		def packageName = DIR.toString().replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "");
		if(isF==1){
			return packageName.substring(0, packageName.length()-1)+ ";";
		}
		def pack = packageName.replaceAll("entity", "");
		def value = pack.toString().substring(0, pack.toString().length()-2);
		return value;
	}

	def _generate(out,className, fields) {
		out.println "package ${_getPackageName(1)}"
		out.println ""
		
		out.println "import com.hcloud.entity.base.Mode;"

		Set types = new HashSet()
		
		fields.each() {
			types.add(it.type)
		}
		
		if (types.contains("Date")) {
			out.println "import java.util.Date;"
		}else if (types.contains("InputStream")) {
			out.println "import java.io.InputStream;"
		}
		if (types.contains("BigDecimal")) {
			out.println "import java.math.BigDecimal;"
		}
		
		out.println "import java.util.ArrayList;"
		out.println "import java.util.List;"
		out.println "import com.alibaba.fastjson.annotation.JSONField;"
		
		
		out.println ""
		out.println "public class $className extends Mode {"
		fields.each() {
//			out.println ""

			// 输出注释
			if (isNotEmpty(it.comment)) {
				out.println "\t/**"
				out.println "\t * ${it.comment}"
				out.println "\t */"
			}
			// 输出成员变量
//			out.println "\tprivate ${it.type} ${it.name};\r\n"
		}
		
		def primarykeys = "\t\tList<String> pris = new ArrayList<String>();\r\n";
		def setFields = "\t\tList<String> fields = new ArrayList<String>();\r\n";
		def autokeys = "\t\tList<String> autokeys = new ArrayList<String>();\r\n";
		def table_name = "";
		
		// 输出get/set方法
		fields.each() {
			out.println ""
			
			def fieldType = "";
			
			def itType = it.type.toString();
			def data_type = it.real_data_type.toString();
			if (data_type.contentEquals("date")) {
				fieldType = "getDate";
			}else if (data_type.contentEquals("datetime")) {
				fieldType = "getDateTime";
			}else if (itType.contains("Integer")) {
				fieldType = "getInt";
			}else if (itType.contains("Boolean")) {
				fieldType = "getBoolean";
			}else if (itType.contains("BigDecimal")) {
				fieldType = "get";
			}else if (itType.contains("String")) {
				fieldType = "getStr";
			}
			if(it.column_key.toString().contains("PRI")){
				primarykeys += "\t\tpris.add(\"${it.name}\");";
			}
			if(it.extra.toString().contains("auto_increment")){
				autokeys += "\t\tautokeys.add(\"${it.name}\");";
			}
			setFields += "\t\tfields.add(\"${it.name}\");\r\n";
			table_name = "\"${it.real_table_name}\"";
			
			if (isNotEmpty(it.comment)) {
				out.println "\t/**"
				out.println "\t * 获取${it.comment}"
				out.println "\t */"
			}
			def actionName = "Boolean".equals(it.type.toString()) ? "is" : "get"
			out.println "\[email protected](name=\"${it.name}\") "
			out.println "\tpublic ${it.type} ${actionName}${_getLumpName(it.name).capitalize()}() {"
			out.println "\t\treturn ${fieldType}(\"${it.name}\"); "
//			out.println "\t\treturn ${it.name};"
			
			out.println "\t}"
			out.println ""
			
			if (isNotEmpty(it.comment)) {
				out.println "\t/**"
				out.println "\t * ${it.comment}"
				out.println "\t */"
			}
			out.println "\tpublic void set${_getLumpName(it.name).capitalize()}(${it.type} ${it.name}) {"
			out.println "\t\tset(\"${it.name}\", ${it.name});"
			out.println "\t}"
		}
		out.println("");
		//输出构造方法
		out.println "\[email protected]"
		out.println "\tpublic void initAttrs() {"
		out.println "${primarykeys} "
		out.println "${setFields}"
		out.println "${autokeys}"
		out.println "\t\tsetPrimarykeys(pris);"
		out.println "\t\tsetFields(fields);"
		out.println "\t\tsetAutokeys(autokeys);"
		out.println "\t\tsetTableName(${table_name});"
		out.println "\t}"
		
		out.println("}");
	}
	def isNotEmpty(content) {
		return content != null && content.toString().trim().length() > 0;
	}
	def ALLTABLESQL = "select * from information_schema.columns where table_schema = '${TABLE_SCHEMA}' ";//查询表结构SQL
	def typeMapping = [
       (~/(?i)bool|bit|tinyint/)                        : "Boolean",
		(~/(?i)int/)                             : "Integer",
		(~/(?i)float|double|decimal|real/)       : "BigDecimal",
		(~/(?i)datetime|timestamp|date|time/)    : "Date",
		(~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
		(~/(?i)/):"String"
	];
}

 

相关标签: 杂乱技术