All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.webapp.utils.mybatis.ClassBuilder Maven / Gradle / Ivy

The newest version!
package com.webapp.utils.mybatis;

import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.entity.annotation.ColType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.webapp.utils.builder.TableBuilder;
import com.webapp.utils.builder.TableBuilder.CMT;
import com.webapp.utils.config.PathUtils;
import com.webapp.utils.string.Utils;
import com.webapp.utils.string.Utils.Symbol;

public class ClassBuilder {

	private static final Logger logger = LoggerFactory.getLogger(ClassBuilder.class);
	private static final String DEF_PKG = "com.webapp.table";
	private Class clz;
	private TableRule tableRule;

	public ClassBuilder(Class clz){
		tableRule = new TableRule(clz);
		tableRule.setSnakeMap(TableBuilder.isSnake());
		tableRule.setComment(TableBuilder.getComment());
		tableRule.setAllNull(TableBuilder.isAllNull());
		this.clz = clz;
	}
	public ClassBuilder table(String table){
		tableRule.setTableName(table);
		return this;
	}
	public ClassBuilder id(String col){
		tableRule.setTableId(col);
		return this;
	}
	public ClassBuilder unique(String ...col) {
		tableRule.setUniqueCol(Arrays.asList(col));
		return this;
	}
	public ClassBuilder notNull(String ...col){
		tableRule.addNotNull(Arrays.asList(col));
		return this;
	}

	public ClassBuilder camel() {
		tableRule.setSnakeMap(false);
		return this;
	}
	public ClassBuilder snake() {
		tableRule.setSnakeMap(true);
		return this;
	}
	public ClassBuilder width(String col, int width) {
		tableRule.addColWidth(col, width);
		return this;
	}
	public ClassBuilder width(Map cloWidth) {
		tableRule.addColWidth(cloWidth);
		return this;
	}
	public ClassBuilder precision(String col, int precision){
		tableRule.addPrecision(col, precision);
		return this;
	}
	public ClassBuilder precision(Map precision){
		tableRule.addPrecision(precision);
		return this;
	}
	public ClassBuilder defVal(String col, String val){
		tableRule.addDefVal(col, val);
		return this;
	}
	public ClassBuilder defVal(Map defVal){
		tableRule.setDefVal(defVal);
		return this;
	}
	public ClassBuilder comment(CMT cmt) {
		tableRule.setComment(cmt.getIndex());
		return this;
	}
	public ClassBuilder type(String col, String type) {
		tableRule.addColType(col, type);
		return this;
	}
	public ClassBuilder timestamp(String ...cols) {
		Arrays.asList(cols).forEach(col->tableRule.addColType(col, "TIMESTAMP"));
		return this;
	}

	private static List modelLines(Class clz){
		List lines = new ArrayList<>();
		String curPath = StringUtils.substringBefore(PathUtils.getCurPath(clz), "target");

		try {
			String path = curPath + "src\\main\\java\\" + clz.getName().replace(".", "\\") + ".java";
			InputStream is = new FileInputStream(path);
			lines = IOUtils.readLines(is, "utf-8");
		} catch (Exception e) {
			logger.error("", e);
		}
		return lines;
	}

	private String createClz(){
		Map ipt = new HashMap<>();
		StringBuffer topStr = new StringBuffer();
		StringBuffer clzStr = new StringBuffer();
		StringBuffer getset = new StringBuffer();

		String name = clz.getSimpleName();
		List lines = modelLines(clz);
		Field[] fields = getAllField(clz);

		topStr.append("package " + tableRule.getPkg() + ";").append(Symbol.Enter);
		topStr.append("import org.nutz.dao.entity.annotation.*;").append(Symbol.Enter);
		clzStr.append("@Table(\"" + tableRule.getTableName() + "\")").append(Symbol.Enter);

		lines.forEach(x->{
			if(x.contains("@Comment")){
				clzStr.append("@Comment(\"" + x.split("@Comment")[1].trim() + "\")").append(Symbol.Enter);
			}
		});

		List uniqueCol = tableRule.getUniqueCol();
		if(!uniqueCol.isEmpty()){
			clzStr.append("@TableIndexes({");
			uniqueCol.forEach(x->{
				clzStr.append(Symbol.Tab).append("@Index(name=\""+x+"\",unique=true,fields={\""+x+"\"})").append(Symbol.Enter);
			});
			clzStr.append("})");
		}

		clzStr.append("public class " + name + "{").append(Symbol.Enter);

		int size = lines.size();
	    for(Field field : fields){
	        String col = field.getName();
	        String type = field.getType().getSimpleName();
	        String typePkg = field.getType().getName();

	        String fieldComm = "";
	        String cp = type + " " + col + ";";
	        for(int i = size-1; i>0; i--){
	        	String line = lines.get(i);
				if(line.contains(cp)){
					if(tableRule.getComment() == 1){//注释在上面
						fieldComm = lines.get(i-1).replace("//", "");
					}else if(tableRule.getComment() == 2){//注释在右边
						fieldComm = StringUtils.substringAfter(line, "//");
					}
					fieldComm = StringUtils.trim(fieldComm).toLowerCase();
					if(fieldComm.contains("timestamp")){
						fieldComm.replaceFirst("timestamp", "");
						tableRule.addColType(col, "TIMESTAMP");
					}
					break;
				}
			}

	        if(!typePkg.startsWith("java.lang") && typePkg.contains(Symbol.Dot)){
	        	ipt.put(type, typePkg);
	        }

	        if(col.equals(tableRule.getTableId())){
	        	clzStr.append(Symbol.Tab).append("@Id").append(Symbol.Enter);
	        }
	        if(tableRule.isSnakeMap()){
	        	clzStr.append(Symbol.Tab).append("@Column(hump = true)").append(Symbol.Enter);
	        }
        	if(tableRule.getDefVal().containsKey(col)){
        		String val = tableRule.getDefVal().get(col);
        		clzStr.append(Symbol.Tab).append("@Default(value = \"" + val + "\")").append(Symbol.Enter);
        	}

        	ColDefineRule cr = tableRule.getColRule().get(col);
        	String colDefine = "";
        	if(StringUtils.isNoneBlank(cr.getCustomType())){
        		colDefine += "customType=\"" + cr.getCustomType() + "\"";
        	}else if(cr.getType() != null){
        		colDefine += "type=ColType." + cr.getType();
        		if(cr.getWidth() != 0){
            		colDefine += ",width=" + cr.getWidth();
            	}
            	if(cr.getPrecision() != 0){
            		colDefine += ",precision=" + cr.getPrecision();
            	}
        	}
        	if(tableRule.isAllNull()){
        		if(cr.getNotNull() == null || cr.getNotNull().equals(false)){
        			colDefine += ",notNull=false";
        		}else if(cr.getNotNull().equals(true)){
        			colDefine += ",notNull=true";
        		}
        	}else {
        		if(cr.getIsNull() == null || cr.getIsNull().equals(false)){
        			colDefine += ",notNull=true";
        		}else if(cr.getIsNull().equals(true)){
        			colDefine += ",notNull=false";
        		}
			}

        	if(StringUtils.isNotEmpty(colDefine)){
        		colDefine = "@ColDefine(" + colDefine + ")";
        		clzStr.append(Symbol.Tab).append(colDefine).append(Symbol.Enter);
        	}

        	if(StringUtils.isNotEmpty(fieldComm)){
        		String comment = "@Comment(\"" + fieldComm + "\")";
        		clzStr.append(Symbol.Tab).append(comment).append(Symbol.Enter);
        	}

	        clzStr.append(Symbol.Tab).append("private " + type + " " + col + ";").append(Symbol.Enter);

	        getset.append(Symbol.Tab).append("public " + type + " get" + Utils.toPascal(col) + "(){").append(Symbol.Enter);
	        getset.append(Symbol.Tab).append("\treturn " + col + ";").append(Symbol.Enter);
	        getset.append(Symbol.Tab).append("}").append(Symbol.Enter);

	        getset.append(Symbol.Tab).append("public void set" + Utils.toPascal(col) + "(" + type + " " + col + "){").append(Symbol.Enter);
	        getset.append(Symbol.Tab).append("\tthis." + col + " = " + col + ";").append(Symbol.Enter);
	        getset.append(Symbol.Tab).append("}").append(Symbol.Enter);
	    }
	    if(tableRule.isHasGetSet()) clzStr.append(getset);
	    clzStr.append("}");

	    ipt.forEach((k,v)->{
	    	topStr.append("import " + v + ";").append(Symbol.Enter);
	    });

	    String result = topStr.append(clzStr).toString();
		return result;
	}

	public void done(String jdbcCfg) {
		String clzStr = createClz();
		TableBuilder.build(jdbcCfg, clzStr, tableRule.getPkg(), tableRule.getClzName());
	}
	public void done() {
		if(StringUtils.isBlank(TableBuilder.getJdbcCfg())){
			logger.error("jdbcCfg is null, please set by TableBuilder.setJdbcCfg() or done(String jdbcCfg)");
		}
		done(TableBuilder.getJdbcCfg());
	}

	public void view() {
		String clzStr = createClz();
		logger.info(Symbol.Enter + clzStr);
	}

	private static  Field[] getAllField(Class clz) {
		List fieldList = new ArrayList<>();
		Class superclz = clz.getSuperclass();
		if(superclz != null){
			fieldList.addAll(Arrays.asList(superclz.getDeclaredFields()));
		}
	    fieldList.addAll(Arrays.asList(clz.getDeclaredFields()));
	    Field[] fields = fieldList.toArray(new Field[]{});
		return fields;
	}
	private static Map getColRuleMap(Field[] fields) {
		Map colRule = new HashMap<>();
		for(Field field : fields){
	        String col = field.getName();
	        String type = field.getType().getSimpleName();
	        if(type.equals(String.class.getSimpleName())){
	        	colRule.put(col, new ColDefineRule(ColType.VARCHAR, 255, 0));
	        }else if(type.equals(Integer.class.getSimpleName()) || type.equals("int")){
	        	colRule.put(col, new ColDefineRule("int", 11, 0));
	        }else if(type.equalsIgnoreCase(Long.class.getSimpleName())){
	        	colRule.put(col, new ColDefineRule("bigint", 20, 0));
	        }else if(type.equalsIgnoreCase(Double.class.getSimpleName())){
	        	colRule.put(col, new ColDefineRule("decimal", TableBuilder.getDeciLength(), TableBuilder.getDeciPrecision()));
	        }else if(type.equals(Date.class.getSimpleName())){
	        	colRule.put(col, new ColDefineRule(ColType.DATETIME, 0, 0));
	        }else {
	        	colRule.put(col, new ColDefineRule("varchar", 255, 0));
			}
		}
		return colRule;
	}

	private static class TableRule {
		private String tableName;
		private Field[] field;
		private String clzName;
		private String pkg;
//		private int defStrWidth;
//		private int defIntWidth;
		private int comment;
		private String tableId;
		private boolean snakeMap;
		private boolean allNull;
		private List uniqueCol = new ArrayList<>();
		private Map defVal = new HashMap<>();
		private Map colRule = new HashMap<>();
		private boolean hasGetSet;

		public void addDefVal(String col, String val) {
			this.defVal.put(Utils.toCamel(col), val);
		}
		public void addPrecision(Map precision) {
			precision.forEach((col, ps)->{
				colRule.get(Utils.toCamel(col)).setPrecision(ps);
			});
		}
		public void addPrecision(String col, int precision) {
			colRule.forEach((colDef, colRule)->{
				if(Utils.toCamel(col).equals(colDef)) colRule.setPrecision(precision);
			});
		}
		public void addColWidth(String col, int width) {
			colRule.forEach((colDef, colRule)->{
				if(Utils.toCamel(col).equals(colDef)) colRule.setWidth(width);
			});
		}
//		public void addColType(Map types) {
//			types.forEach((col, type)->{
//				colRule.get(Utils.toCamel(col)).setCustomType(type);
//			});
//		}
		public void addColType(String col, String type) {
			colRule.forEach((colDef, colRule)->{
				if(Utils.toCamel(col).equals(colDef)) colRule.setCustomType(type);
			});
		}
		public void addColWidth(Map cloWidth) {
			cloWidth.forEach((col, width)->{
				colRule.get(Utils.toCamel(col)).setWidth(width);
			});
		}
		public void addNotNull(List notNull) {
			notNull.forEach(col->colRule.get(Utils.toCamel(col)).setNotNull(true));
		}
		public  TableRule(Class clz) {
			this.setField(getAllField(clz));
//			this.setDefIntWidth(11);
//			this.setDefStrWidth(255);
			this.setTableId("id");
			this.setSnakeMap(true);
			this.setAllNull(false);
//			this.setComment(CMT.UP.getIndex());
			this.setHasGetSet(false);
			this.setPkg(DEF_PKG);
			this.setTableName(Utils.toSnake(clz.getSimpleName()));
			this.setClzName(clz.getSimpleName());
			this.setColRule(getColRuleMap(this.getField()));
		}

		public String getTableName() {
			return tableName;
		}
		public void setTableName(String tableName) {
			this.tableName = tableName;
		}
		public Field[] getField() {
			return field;
		}
		public void setField(Field[] field) {
			this.field = field;
		}
		public String getClzName() {
			return clzName;
		}
		public void setClzName(String clzName) {
			this.clzName = clzName;
		}
		public String getPkg() {
			return pkg;
		}
		public void setPkg(String pkg) {
			this.pkg = pkg;
		}
//		public int getDefStrWidth() {
//			return defStrWidth;
//		}
//		public void setDefStrWidth(int defStrWidth) {
//			this.defStrWidth = defStrWidth;
//		}
//		public int getDefIntWidth() {
//			return defIntWidth;
//		}
//		public void setDefIntWidth(int defIntWidth) {
//			this.defIntWidth = defIntWidth;
//		}
		public int getComment() {
			return comment;
		}
		public void setComment(int comment) {
			this.comment = comment;
		}
		public String getTableId() {
			return tableId;
		}
		public void setTableId(String tableId) {
			this.tableId = tableId;
		}
		public List getUniqueCol() {
			return uniqueCol;
		}
		public void setUniqueCol(List uniqueCol) {
			this.uniqueCol = uniqueCol;
		}
		public boolean isSnakeMap() {
			return snakeMap;
		}
		public void setSnakeMap(boolean snakeMap) {
			this.snakeMap = snakeMap;
		}
		public boolean isAllNull() {
			return allNull;
		}
		public void setAllNull(boolean allNull) {
			this.allNull = allNull;
		}
		public Map getDefVal() {
			return defVal;
		}
		public void setDefVal(Map defVal) {
			this.defVal = defVal;
		}
		public boolean isHasGetSet() {
			return hasGetSet;
		}
		public void setHasGetSet(boolean hasGetSet) {
			this.hasGetSet = hasGetSet;
		}
		public Map getColRule() {
			return colRule;
		}
		public void setColRule(Map colRule) {
			this.colRule = colRule;
		}
	}

	private static class ColDefineRule {
//		private boolean auto;
		private ColType type;
		private int width;
		private int precision;
		private Boolean notNull;
		private Boolean isNull;
		private String customType;

		public ColDefineRule(ColType type, int width, int precision) {
			this.type = type;
//			this.auto = false;
			this.width = width;
			this.precision = precision;
			this.notNull = null;
			this.isNull = null;
		}
		public ColDefineRule(String customType, int width, int precision) {
			if(width != 0 && precision != 0){
				this.customType = customType + "(" + width + "," + precision + ")";
			}else if(width !=0 && precision ==0){
				this.customType = customType + "(" + width + ")";
			}else {
				this.customType = customType;
			}
//			this.auto = false;
			this.width = width;
			this.precision = precision;
			this.notNull = null;
			this.isNull = null;
		}
//		public boolean isAuto() {
//			return auto;
//		}
//		public void setAuto(boolean auto) {
//			this.auto = auto;
//		}
		public ColType getType() {
			return type;
		}
		public void setType(ColType type) {
			this.type = type;
		}
		public int getWidth() {
			return width;
		}
		public void setWidth(int width) {
			this.width = width;
		}
		public int getPrecision() {
			return precision;
		}
		public void setPrecision(int precision) {
			this.precision = precision;
		}
		public Boolean getNotNull() {
			return notNull;
		}
		public void setNotNull(Boolean notNull) {
			this.notNull = notNull;
		}
		public Boolean getIsNull() {
			return isNull;
		}
		public void setIsNull(Boolean isNull) {
			this.isNull = isNull;
		}
		public String getCustomType() {
			return customType;
		}
		public void setCustomType(String customType) {
			this.customType = customType;
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy