根据数据库自动生成java代码

 

package com.wei.test_anyway.temp;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chengwei
 * @date 2017年3月10日 下午6:11:02
 * @Description:  根据数据库生成实体类,Mapper,mapper.xml,Service等文件
 * 该工具类需要用到 mysql-connector-java包
 * 
 * 注意要修改的值有 prifix_module_name, suffix_module_name, url, table_name, useListMeathod
 */
public class EntityUtil {
	// 配置文件包名称 , 这些值需要根据各自的项目配置
	private final String prifix_module_name = "com.wei.learn_springboot";

	// 配置模块名(例: .user)
	private final String suffix_module_name = "";
	
	private final String bean_package = prifix_module_name + ".entity" + suffix_module_name;

	private final String dto_package = prifix_module_name + ".entity.vo" + suffix_module_name;

	private final String mapper_package = prifix_module_name + ".dao" + suffix_module_name;

	private final String service_package = prifix_module_name + ".service" + suffix_module_name;

	private final String serviceimpl_package = prifix_module_name + ".service"+ suffix_module_name +".impl";


	// 配置数据库连接信息
	private final String drivername = "com.mysql.jdbc.Driver";

	private final String user = "root";

	private final String password = "123456";

	private final String url = "jdbc:mysql://localhost:3306/springboot_test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false";

	/**  用于指定生成类文件的表, 当有多个表时表之间用逗号间隔(例: "student, teacher") 当值为空时会将数据库的所有表都生成类文件 */
	private final String table_name = "";


	// 定义数据库常用类型
	private final String type_char = "char";

	private final String type_date = "date";

	private final String type_timestamp = "timestamp";

	private final String type_int = "int";

	private final String type_bigint = "bigint";

	private final String type_double = "double";

	private final String type_text = "text";

	private final String type_bit = "bit";

	private final String type_decimal = "decimal";

	private final String type_blob = "blob";

	// 配置文件存放地址
	private static final String PACKAGE_PATH = "D:\\workspace\\entity\\";

	private final String bean_path = PACKAGE_PATH + "entity_bean";

	private final String dto_path = PACKAGE_PATH + "entity_vo";

	private final String service_path = PACKAGE_PATH + "entity_service";

	private final String mapper_path = PACKAGE_PATH + "entity_mapper";

	private final String xml_path = PACKAGE_PATH + "entity_mapper/xml";

	// 方法统一命名
	private final String save = "insert";

	private final String saveSelective = "insertSelective";

	private final String update = "updateByPrimaryKey";

	private final String updateSelective = "updateByPrimaryKeySelective";

	private final String countTotalNum = "count";

	private final String queryPage = "list";

	private final String queryById = " selectByPrimaryKey";

	private final String delete = "deleteByPrimaryKey";

	// sql语句
	private final String showTablesName = "show tables"; // 获取数据库的所有表名

	private final String showTablesInfo = "show table status"; // 获取数据库的所有表详情信息(包括注释)

	private final String showFields = "show full fields from "; // 获取指定表的所有字段详情

	// 定义系统中使用到的全局变量
	private String tableName;

	private String beanName;

	private String dtoName;

	private String serviceName;

	private String serviceImplName;

	private String lowerBeanName;

	private String mapperName;

	private List<String> columns = new ArrayList<>();

	private List<String> types = new ArrayList<>();

	private List<String> comments = new ArrayList<>();

	// 判断是否是自动生成主键
	private boolean isAutoIncrementKey = false;
	private String keyColumnType;
	private String keyColumnName;

	private Connection conn;

	// 常用的配置项

	/** 表名中的这些值将不会转换为类名的一部分 */
	private final String[] table_prefixs = { "app", "bi"};

	/** 指定是否生成分页查询方法, false为不生成, true为生成 */
	private Boolean useListMeathod = false;

	/**
	 * 删除指定目录下所有文件,若目录不存在则创建该目录
	 */
	private static void mkdirs(Runtime runtime) throws IOException {
		File file = new File(PACKAGE_PATH);
		if (file.exists()) {
			runtime.exec("cmd /c del /q/a/f/s " + file.getAbsolutePath());
		}
		file.mkdirs();
	}

	/**
	 * 获取连接
	 */
	private void initConnection() throws ClassNotFoundException, SQLException {
		Class.forName(drivername);
		conn = DriverManager.getConnection(url, user, password);
	}

	/**
	 * 获取所有的表名
	 */
	private List<String> getTables() throws SQLException {
		List<String> tables = new ArrayList<>();
		PreparedStatement pstate = conn.prepareStatement(showTablesName);
		ResultSet results = pstate.executeQuery();
		while (results.next()) {
			String tableName = results.getString(1);
			// if ( tableName.toLowerCase().startsWith("yy_") ) {
			tables.add(tableName);
			// }
		}
		return tables;
	}

	/**
	 * 根据表名生成实体类名称及所有相关的文件名
	 */
	private void initNameByTable(String table) {
		tableName = table;
		beanName = getBeanName(table);
		lowerBeanName = lowerCaseFirstLitter(beanName);
		dtoName = beanName + "Vo";
		mapperName = beanName + "Mapper";
		serviceName = beanName + "Service";
		serviceImplName = serviceName + "Impl";
	}

	/**
	 * 根据表名获取实体类名
	 */
	private String getBeanName(String table) {
		StringBuilder entityName = new StringBuilder(table.length());
		String tableLower = table.toLowerCase();
		String[] tables = tableLower.split("_");
		String temp;
		for (int i = 0; i < tables.length; i++) {
			temp = tables[i].trim();
			if (canUseTemp(temp)) {
				entityName.append(upperCaseFirstLitter(temp));
			}
		}
		return entityName.toString();
	}

	/**
	 * 判断表名前缀是否要加到实体类名上
	 */
	private Boolean canUseTemp(String temp) {
		if (isEmpty(temp)) {
			return false;
		}
		for (String tablePrefix : table_prefixs) {
			if (tablePrefix.equalsIgnoreCase(temp)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 获取实体类属性的数据类型
	 */
	private String processType(String type) {
		if (type.indexOf(type_char) > -1) {
			return "String";
		} else if (type.indexOf(type_bigint) > -1) {
			return "Long";
		} else if (type.indexOf(type_int) > -1) {
			return "Integer";
		} else if (type.indexOf(type_date) > -1) {
			return "Date";
		} else if (type.indexOf(type_text) > -1) {
			return "String";
		} else if (type.indexOf(type_timestamp) > -1) {
			return "Date";
		} else if (type.indexOf(type_bit) > -1) {
			return "Boolean";
		} else if (type.indexOf(type_decimal) > -1) {
			return "BigDecimal";
		} else if (type.indexOf(type_blob) > -1) {
			return "byte[]";
		} else if(type.indexOf(type_double) > -1){
			return "Double";
		}
		return null;
	}

	/**
	 * 将字段名转换为实体类的属性名
	 */
	private String processField(String field) {
		StringBuilder sb = new StringBuilder(field.length());
		String[] fields = field.split("_");
		sb.append(fields[0]);
		for (int i = 1; i < fields.length; i++) {
			sb.append(upperCaseFirstLitter(fields[i].trim()));
		}
		return sb.toString();
	}

	/**
	 * 构建类上面的注释
	 */
	private void buildClassComment(BufferedWriter bw, String text) throws IOException {
		bw.newLine();
		bw.newLine();
		bw.write("/**");
		bw.newLine();
		bw.write(" * " + text);
		bw.newLine();
		bw.write(" */");
	}

	/**
	 * 构建方法上面的注释
	 */
	private void buildMethodComment(BufferedWriter bw, String text) throws IOException {
		bw.newLine();
		bw.write("\t/**" + text + "*/");
	}

	/**
	 * 生成实体类
	 */
	private void buildEntityBean(List<String> columns, List<String> types, List<String> comments, String tableComment)
			throws IOException {
		instanceFolder(bean_path);
		BufferedWriter bw = instanceBufferedWriter(bean_path, beanName + ".java");
		writeBeanHead(tableComment, bw);
		writeBeanColumns(columns, types, comments, bw);
		// writeGetSetMethod(columns, types, bw);
		// writeGetByDto(columns, bw);
		writeEnd(bw);
	}

	/**
	 * 写类结尾处代码
	 */
	private void writeEnd(BufferedWriter bw) throws IOException {
		bw.newLine();
		bw.write("}");
		bw.newLine();
		bw.flush();
		bw.close();
	}

	/**
	 * 写根据dto生成实体类方法
	 */
	private void writeGetByDto(List<String> columns, BufferedWriter bw) throws IOException {
		bw.write("public " + beanName + " get" + beanName + "(" + dtoName + " vo){");
		bw.newLine();
		bw.write("\t" + beanName + " " + lowerBeanName + " = new " + beanName + "();");
		bw.newLine();
		for (int i = 1; i < columns.size(); i++) {
			String fieldName = upperCaseFirstLitter(processField(columns.get(i)));
			bw.write("\t" + lowerBeanName + ".set" + fieldName + "(vo.get" + fieldName + "());");
			bw.newLine();
		}
		bw.write("\treturn " + lowerBeanName);
		bw.newLine();
		bw.write("\t}");
		bw.newLine();
	}

	/**
	 * 写实体类的get,set方法
	 */
	private void writeGetSetMethod(List<String> columns, List<String> types, BufferedWriter bw) throws IOException {
		String uppperField = null;
		String lowerField = null;
		String tempType = null;
		for (int i = 0; i < columns.size(); i++) {
			tempType = processType(types.get(i));
			lowerField = processField(columns.get(i));
			uppperField = upperCaseFirstLitter(lowerField);
			bw.newLine();
			bw.write("\tpublic void set" + uppperField + "(" + tempType + " " + lowerField + "){");
			bw.newLine();
			bw.write("\t\tthis." + lowerField + " = " + lowerField + ";");
			bw.newLine();
			bw.write("\t}");
			bw.newLine();
			bw.newLine();
			bw.write("\tpublic " + tempType + " get" + uppperField + "(){");
			bw.newLine();
			bw.write("\t\treturn this." + lowerField + ";");
			bw.newLine();
			bw.write("\t}");
			bw.newLine();
		}
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 写实体类属性代码
	 */
	private void writeBeanColumns(List<String> columns, List<String> types, List<String> comments, BufferedWriter bw)
			throws IOException {
		for (int i = 0; i < columns.size(); i++) {
			if (isNotEmpty(comments.get(i))) {
				bw.write("\t/**" + comments.get(i) + "*/");
				bw.newLine();
			}
			bw.write("\tprivate " + processType(types.get(i)) + " " + processField(columns.get(i)) + ";");
			bw.newLine();
			bw.newLine();
		}
		bw.newLine();
	}

	/**
	 * 写实体类头部代码
	 */
	private void writeBeanHead(String tableComment, BufferedWriter bw) throws IOException {
		bw.write("package " + bean_package + ";");
		bw.newLine();
		bw.write("import java.io.Serializable;");
		bw.newLine();
		bw.write("import java.util.Date;");
		bw.newLine();
		buildClassComment(bw, tableComment + "实体类");
		bw.newLine();
		bw.write("public class " + beanName + " implements Serializable {");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 根据路径创建文件及输出流
	 */
	private BufferedWriter instanceBufferedWriter(String parent, String child) throws FileNotFoundException {
		File beanFile = new File(parent, child);
		return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(beanFile)));
	}

	/**
	 * 根据路径创建目录
	 */
	private void instanceFolder(String folderPath) {
		File folder = new File(folderPath);
		if (!folder.exists()) {
			folder.mkdir();
		}
	}

	/**
	 * 生成dto
	 */
	private void buildEntityDto(List<String> columns, List<String> types, List<String> comments, String tableComment)
			throws IOException {
		instanceFolder(dto_path);
		BufferedWriter bw = instanceBufferedWriter(dto_path, dtoName + ".java");
		writeDtoHead(tableComment, bw);
		writeDtoClumns(columns, types, comments, bw);
		writeEnd(bw);
	}

	/**
	 * 写DTO类属性代码
	 */
	private void writeDtoClumns(List<String> columns, List<String> types, List<String> comments, BufferedWriter bw)
			throws IOException {
		String type = "";
		for (int i = 0; i < columns.size(); i++) {
			if (isNotEmpty(comments.get(i))) {
				bw.write("\t/**" + comments.get(i) + "*/");
				bw.newLine();
			}
			if (types.get(i).indexOf(type_date) > -1 || types.get(i).indexOf(type_timestamp) > -1) {
				type = "char";
			} else {
				type = types.get(i);
			}
			bw.write("\tprivate " + processType(type) + " " + processField(columns.get(i)) + ";");
			bw.newLine();
			bw.newLine();
		}
		bw.newLine();
	}

	/**
	 * 写DTO类头部代码
	 */
	private void writeDtoHead(String tableComment, BufferedWriter bw) throws IOException {
		bw.write("package " + dto_package + ";");
		bw.newLine();
		buildClassComment(bw, tableComment + "页面显示对象");
		bw.newLine();
		bw.write("public class " + dtoName + " {");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 构建方法代码
	 * 
	 * @param comment
	 *            方法注释
	 * @param returnType
	 *            方法返回类型
	 * @param name
	 *            方法名
	 * @param param
	 *            方法参数
	 */
	private void buildMethod(BufferedWriter bw, String comment, String returnType, String name, String param)
			throws IOException {
		buildMethodComment(bw, comment);
		bw.newLine();
		String result = MessageFormat.format("\t{0} {1}({2});", returnType, name, param);
		bw.write(result);
		bw.newLine();
	}

	/**
	 * 构建Dao文件
	 */
	private void buildMapper() throws IOException {
		instanceFolder(mapper_path);
		BufferedWriter bw = instanceBufferedWriter(mapper_path, mapperName + ".java");
		writeMapperHead(bw);
		writeMethod(bw);
		writeEnd(bw);
	}

	/**
	 * 写Mapper及Service中方法代码
	 */
	private void writeMethod(BufferedWriter bw) throws IOException {
		buildMethod(bw, "查询(根据主键ID查询", beanName, queryById, keyColumnType+" "+processField(keyColumnName));
		buildMethod(bw, "删除(根据主键ID删除)", "int", delete, keyColumnType+" "+processField(keyColumnName));
		buildMethod(bw, "添加", "int", save, beanName + " " + lowerBeanName);
		buildMethod(bw, "添加 (匹配有值的字段)", "int", saveSelective, beanName + " " + lowerBeanName);
		buildMethod(bw, "修改", "int", update, beanName + " " + lowerBeanName);
		buildMethod(bw, "修改 (匹配有值的字段)", "int", updateSelective, beanName + " " + lowerBeanName);
		if (useListMeathod) {
			buildMethod(bw, "根据条件分页查询", "List<" + beanName + "Vo>", queryPage, "Map<String, Object> param");
			buildMethod(bw, "查询总条数", "int", countTotalNum, "Map<String, Object> param");
		}
	}

	/**
	 * 写Mapper类头部代码
	 */
	private void writeMapperHead(BufferedWriter bw) throws IOException {
		bw.write("package " + mapper_package + ";");
		bw.newLine();
		bw.newLine();
		bw.write("import " + bean_package + "." + beanName + ";");
		bw.newLine();
		bw.write("import java.util.List;");
		bw.newLine();
		bw.write("import java.util.Map;");
		bw.newLine();
		bw.write("import org.apache.ibatis.annotations.Param;");
		buildClassComment(bw, mapperName + "数据库操作接口类");
		bw.newLine();
		bw.write("public interface " + mapperName + "{");
		bw.newLine();
	}

	/**
	 * 构建Service文件
	 */
	private void buildServie() throws IOException {
		instanceFolder(service_path);
		BufferedWriter bw = instanceBufferedWriter(service_path, serviceName + ".java");
		writeServiceHead(bw);
		writeMethod(bw);
		writeEnd(bw);
	}

	/**
	 * 写service接口头部代码
	 */
	private void writeServiceHead(BufferedWriter bw) throws IOException {
		bw.write("package " + service_package + ";");
		bw.newLine();
		bw.newLine();
		bw.write("import " + bean_package + "." + beanName + ";");
		bw.newLine();
		bw.write("import java.util.List;");
		bw.newLine();
		bw.write("import java.util.Map;");
		bw.newLine();
		bw.write("import org.apache.ibatis.annotations.Param;");
		buildClassComment(bw, serviceName + "数据库操作接口类");
		bw.newLine();
		bw.write("public interface " + serviceName + " {");
		bw.newLine();
	}

	/**
	 * 构建ServiceImpl文件
	 */
	private void buildServieImpl() throws IOException {
		instanceFolder(service_path);
		BufferedWriter bw = instanceBufferedWriter(service_path, serviceImplName + ".java");
		writeServiceImplHead(bw);
		writeServieImplMethod(bw);
		writeEnd(bw);
	}

	/**
	 * 写serveImpl中的方法
	 */
	private void writeServieImplMethod(BufferedWriter bw) throws IOException {
		String lowerMapperName = lowerCaseFirstLitter(mapperName);
		buildServiceImplMethod(bw, beanName, queryById, keyColumnType+" "+processField(keyColumnName), lowerMapperName);
		buildServiceImplMethod(bw, "int", delete, keyColumnType+" "+processField(keyColumnName), lowerMapperName);
		buildServiceImplMethod(bw, "int", save, beanName + " " + lowerBeanName, lowerMapperName);
		buildServiceImplMethod(bw, "int", saveSelective, beanName + " " + lowerBeanName, lowerMapperName);
		buildServiceImplMethod(bw, "int", update, beanName + " " + lowerBeanName, lowerMapperName);
		buildServiceImplMethod(bw, "int", updateSelective, beanName + " " + lowerBeanName, lowerMapperName);
		if (useListMeathod) {
			buildServiceImplMethod(bw, "List<" + beanName + "Vo>", queryPage, "Map<String, Object> param",
					lowerMapperName);
			buildServiceImplMethod(bw, "int", countTotalNum, "Map<String, Object> param", lowerMapperName);
		}
	}

	/**
	 * 写serveImpl中的方法
	 */
	private void buildServiceImplMethod(BufferedWriter bw, String returnType, String name, String param,
			String lowerMapperName) throws IOException {
		bw.write("\t@Override");
		bw.newLine();
		bw.write(MessageFormat.format("\tpublic {0} {1}({2})", returnType, name, param));
		bw.write("{");
		bw.newLine();
		bw.write(MessageFormat.format("\t\treturn {0}.{1}({2});", lowerMapperName, name.trim(),
				param.substring(param.lastIndexOf(" ") + 1)));
		bw.newLine();
		bw.write("\t}");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 写serviceImpl头部代码
	 */
	private void writeServiceImplHead(BufferedWriter bw) throws IOException {
		String lowerMapperName = lowerCaseFirstLitter(mapperName);
		bw.write("package " + serviceimpl_package + ";");
		bw.newLine();
		bw.newLine();
		bw.write("import java.util.List;");
		bw.newLine();
		bw.write("import org.springframework.beans.factory.annotation.Autowired;");
		bw.newLine();
		bw.write("import org.springframework.stereotype.Service;");
		bw.newLine();
		bw.write("import " + bean_package + "." + beanName + ";");
		bw.newLine();
		buildClassComment(bw, serviceImplName + "数据库操作接口类");
		bw.newLine();
		bw.newLine();
		bw.write("@Service(\"" + serviceName + "\")");
		bw.newLine();
		bw.write("public class " + serviceImplName + " implements " + serviceName + " {");
		bw.newLine();
		bw.newLine();
		bw.write("\t@Autowired");
		bw.newLine();
		bw.write("\tprivate " + mapperName + " " + lowerMapperName + ";");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 构建实体类映射XML文件
	 */
	private void buildMapperXml(List<String> columns, List<String> types, List<String> comments) throws IOException {
		instanceFolder(xml_path);
		BufferedWriter bw = instanceBufferedWriter(xml_path, mapperName + ".xml");
		writeMapperXmlHead(bw);
		writeMapperXmlResultMap(columns, comments, bw);
		buildSQL(bw, columns, types);
		bw.write("</mapper>");
		bw.flush();
		bw.close();
	}

	/**
	 * 写Mappper.xml文件映射代码
	 */
	private void writeMapperXmlResultMap(List<String> columns, List<String> comments, BufferedWriter bw)
			throws IOException {
		bw.write("\t<!--实体映射-->");
		bw.newLine();
		bw.write(MessageFormat.format("\t<resultMap id=\"{0}ResultMap\" type=\"{1}.{2}\">",
				lowerCaseFirstLitter(beanName), bean_package, beanName));
		bw.newLine();
		bw.write("\t\t<!--" + comments.get(0) + "-->");
		bw.newLine();
		bw.write("\t\t<id property=\"" + processField(columns.get(0)) + "\" column=\"" + columns.get(0) + "\" />");
		bw.newLine();
		int size = columns.size();
		for (int i = 1; i < size; i++) {
			if(isNotEmpty(comments.get(i))){
				bw.write("\t\t<!--" + comments.get(i) + "-->");
				bw.newLine();
			}
			bw.write("\t\t<result property=\"" + processField(columns.get(i)) + "\" column=\"" + columns.get(i)
					+ "\" />");
			bw.newLine();
		}
		bw.write("\t</resultMap>");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 写Mapper.xml文件头部代码
	 */
	private void writeMapperXmlHead(BufferedWriter bw) throws IOException {
		bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		bw.newLine();
		bw.write(
				"<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"  \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">");
		bw.newLine();
		bw.write("<mapper namespace=\"" + mapper_package + "." + mapperName + "\">");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 写Mapper.xml增删改查等语句
	 */
	private void buildSQL(BufferedWriter bw, List<String> columns, List<String> types) throws IOException {
		selectByPrimaryKey(bw, columns, types);
		insert(bw, columns);
		insertSelective(bw, columns);
		updateByPrimaryKey(bw, columns);
		updateByPrimaryKeySelective(bw, columns);
		deleteByPrimaryKey(bw, columns, types);
		list(bw, columns);
	}

	/**
	 * 写list方法相应个的sql语句
	 */
	private void list(BufferedWriter bw, List<String> columns) throws IOException {
		if(useListMeathod){
			listConditionSql(bw, columns);
			listSql(bw, columns);
			countSql(bw, columns);
		}
	}

	/**
	 * 根据条件查询列表 
	 */
	private void listSql(BufferedWriter bw, List<String> columns) throws IOException {
		bw.write("\t<!-- 根据条件查询列表 -->");
		bw.newLine();
		bw.write(MessageFormat.format("\t<select id=\"list\" resultType=\"{0}.{1}\" parameterType=\"map\">",
				dto_package, beanName + "Vo"));
		bw.newLine();
		bw.write("\t\t SELECT");
		bw.newLine();
		for (int i = 0; i < columns.size(); i++) {
			bw.write(MessageFormat.format("\t\t\ta.{0} AS {1}", columns.get(i), processField(columns.get(i))));
			if (i != columns.size() - 1) {
				bw.write(",");
				bw.newLine();
			}
		}
		bw.newLine();
		bw.write("\t\t <include refid=\"listConditionSql\"/>");
		bw.newLine();
		bw.write("\t</select>");
		bw.newLine();
		bw.newLine();
	}
	
	/**
	 * 根据条件获取总条数
	 */
	private void countSql(BufferedWriter bw, List<String> columns) throws IOException {
		bw.write("\t<!-- 根据条件获取总条数 -->");
		bw.newLine();
		bw.write("\t<select id=\"count\" resultType=\"integer\" parameterType=\"map\">");
		bw.newLine();
		bw.write("\t\t SELECT");
		bw.newLine();
		bw.write("\t\t\t COUNT(*)");
		bw.newLine();
		bw.write("\t\t <include refid=\"listConditionSql\"/>");
		bw.newLine();
		bw.write("\t</select>");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 抽取列表查询条件
	 */
	private void listConditionSql(BufferedWriter bw, List<String> columns) throws IOException {
		bw.write("\t<!-- 抽取列表查询条件 -->");
		bw.newLine();
		bw.write("\t<sql id=\"listConditionSql\">");
		bw.newLine();
		bw.write("\t\t FROM " + tableName +" AS a");
		bw.newLine();
		bw.write("\t\t <where>");
		for (String colum : columns) {
			bw.newLine();
			bw.write(MessageFormat.format("\t\t\t <if test=\"{0} != null and {0} != ''''\">", processField(colum)));
			bw.newLine();
			bw.write(MessageFormat.format("\t\t\t\t AND a.{0} = #'{'{1}'}'", colum, processField(colum)));
			bw.newLine();
			bw.write("\t\t\t </if>");
		}
		bw.newLine();
		bw.write("\t\t </where>");
		bw.newLine();
		bw.write("\t</sql>");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 修改(匹配有值的字段)
	 */
	private void updateByPrimaryKey(BufferedWriter bw, List<String> columns) throws IOException {
		int size = columns.size();
		bw.write("\t<!-- 修 改-->");
		bw.newLine();
		bw.write("\t<update id=\"" + update + "\" parameterType=\"" + bean_package +"."+ beanName + "\">");
		bw.newLine();
		bw.write("\t\t UPDATE " + tableName);
		bw.newLine();
		bw.write("\t\t SET ");

		bw.newLine();
		String tempField = null;
		for (int i = 1; i < size; i++) {
			tempField = processField(columns.get(i));
			bw.write("\t\t\t " + columns.get(i) + " = #{" + tempField + "}");
			if (i != size - 1) {
				bw.write(",");
			}
			bw.newLine();
		}

		bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
		bw.newLine();
		bw.write("\t</update>");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 修改(匹配有值的字段)
	 */
	private void updateByPrimaryKeySelective(BufferedWriter bw, List<String> columns) throws IOException {
		int size = columns.size();
		bw.write("\t<!-- 修 改(匹配有值的字段)-->");
		bw.newLine();
		bw.write("\t<update id=\"" + updateSelective.trim() + "\" parameterType=\"" + bean_package +"."+ beanName
				+ "\">");
		bw.newLine();
		bw.write("\t\t UPDATE " + tableName);
		bw.newLine();
		bw.write(" \t\t <set> ");
		bw.newLine();

		String tempField = null;
		for (int i = 1; i < size; i++) {
			tempField = processField(columns.get(i));
			bw.write("\t\t\t<if test=\"" + tempField + " != null\">");
			bw.newLine();
			bw.write("\t\t\t\t " + columns.get(i) + " = #{" + tempField + "},");
			bw.newLine();
			bw.write("\t\t\t</if>");
			bw.newLine();
		}

		bw.newLine();
		bw.write(" \t\t </set>");
		bw.newLine();
		bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
		bw.newLine();
		bw.write("\t</update>");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * insert方法(匹配有值的字段)
	 */
	private void insertSelective(BufferedWriter bw, List<String> columns) throws IOException {
		int size = columns.size();
		bw.write("\t<!-- 添加 (匹配有值的字段)-->");
		bw.newLine();
		String useGeneratedKey = "";
		if (isAutoIncrementKey) {
			useGeneratedKey = " useGeneratedKeys=\"true\" keyProperty=\"" + processField(keyColumnName) + "\" ";
		}
		bw.write("\t<insert id=\"" + saveSelective.trim() + "\" parameterType=\"" + bean_package + "." + beanName
				+ "\"" + useGeneratedKey + ">");
		bw.newLine();
		bw.write("\t\t INSERT INTO " + tableName);
		bw.newLine();
		bw.write("\t\t <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\" >");
		bw.newLine();

		String tempField = null;
		for (int i = 0; i < size; i++) {
			tempField = processField(columns.get(i));
//			tempField = 0 == i ? "null" : tempField;
			bw.write("\t\t\t<if test=\"" + tempField + " != null\">");
			bw.newLine();
			bw.write("\t\t\t\t " + columns.get(i) + ",");
			bw.newLine();
			bw.write("\t\t\t</if>");
			bw.newLine();
		}

		bw.newLine();
		bw.write("\t\t </trim>");
		bw.newLine();

		bw.write("\t\t <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\" >");
		bw.newLine();

		tempField = null;
		for (int i = 0; i < size; i++) {
			tempField = processField(columns.get(i));
			bw.write("\t\t\t<if test=\"" + tempField + "!=null\">");
			bw.newLine();
			bw.write("\t\t\t\t #{" + tempField + "},");
			bw.newLine();
			bw.write("\t\t\t</if>");
			bw.newLine();
		}

		bw.write("\t\t </trim>");
		bw.newLine();
		bw.write("\t</insert>");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 添加insert方法
	 */
	private void insert(BufferedWriter bw, List<String> columns) throws IOException {
		int size = columns.size();
		bw.write("\t<!-- 添加 -->");
		bw.newLine();
		String useGeneratedKey = "";
		if(isAutoIncrementKey){
			useGeneratedKey = " useGeneratedKeys=\"true\" keyProperty=\""+ processField(keyColumnName) +"\" ";
		}
		bw.write("\t<insert id=\"" + save + "\" parameterType=\"" + bean_package + "." + beanName + "\"" +
				useGeneratedKey + ">");
		bw.newLine();
		bw.write("\t\tINSERT INTO " + tableName + "(");
		writeClumnList(bw, columns);
		bw.write("\t\t)VALUES(");
		bw.newLine();
		for (int i = 0; i < size; i++) {
			bw.write("\t\t\t");
			bw.write("#{" + processField(columns.get(i)) + "}");
			if (i != size - 1) {
				bw.write(",");
			}
			bw.newLine();
		}
		bw.write("\t\t");
		bw.write(") ");
		bw.newLine();
		bw.write("\t</insert>");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 删除(根据主键ID删除)
	 */
	private void deleteByPrimaryKey(BufferedWriter bw, List<String> columns, List<String> types) throws IOException {
		bw.write("\t<!--删除:根据主键ID删除-->");
		bw.newLine();
		bw.write("\t<delete id=\"" + delete + "\" parameterType=\"java.lang." + processType(types.get(0)) + "\">");
		bw.newLine();
		bw.write("\t\t DELETE FROM " + tableName);
		bw.newLine();
		bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
		bw.newLine();
		bw.write("\t</delete>");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 查询(根据主键ID查询)
	 */
	private void selectByPrimaryKey(BufferedWriter bw, List<String> columns, List<String> types) throws IOException {
		bw.write("\t<!-- 查询(根据主键ID查询) -->");
		bw.newLine();
		bw.write(
				MessageFormat.format("\t<select id=\"{0}\" resultMap=\"{1}ResultMap\" parameterType=\"java.lang.{2}\">",
						queryById.trim(), lowerCaseFirstLitter(beanName), processType(types.get(0))));
		bw.newLine();
		bw.write("\t\t SELECT");
		writeClumnList(bw, columns);
		bw.write("\t\t FROM " + tableName);
		bw.newLine();
		bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
		bw.newLine();
		bw.write("\t</select>");
		bw.newLine();
		bw.newLine();
	}

	/**
	 * 写mapper.xml中所有列名的<sql>标签
	 */
	private void writeClumnList(BufferedWriter bw, List<String> columns) throws IOException {
		int size = columns.size();
		bw.newLine();
		for (int i = 0; i < size; i++) {
			bw.write("\t\t\t" + columns.get(i));
			if (i != size - 1) {
				bw.write(",");
				bw.newLine();
			}
		}
		bw.newLine();
	}

	/**
	 * 获取所有的数据库表名及注释
	 */
	private Map<String, String> getTableComment() throws SQLException {
		Map<String, String> maps = new HashMap<>();
		PreparedStatement pstate = conn.prepareStatement(showTablesInfo);
		ResultSet results = pstate.executeQuery();
		while (results.next()) {
			String tableName = results.getString("NAME");
			String comment = results.getString("COMMENT");
			maps.put(tableName, comment);
		}
		return maps;
	}

	public Boolean isEmpty(String str) {
		return null == str || "".equals(str);
	}

	public Boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	/**
	 * 将字符串首字母小写
	 */
	public String lowerCaseFirstLitter(String str) {
		if (isEmpty(str)) {
			return "";
		} else {
			return str.substring(0, 1).toLowerCase() + str.substring(1);
		}
	}

	/**
	 * 将字符串首字母大写
	 */
	public String upperCaseFirstLitter(String str) {
		if (isEmpty(str)) {
			return "";
		} else {
			return str.substring(0, 1).toUpperCase() + str.substring(1);
		}
	}


	/**
	 * 根据某一个表生成实体类,dto,service,mapper,mapper.xml
	 */
	private void generateByTable(Map<String, String> tableComments, String table) throws SQLException, IOException {
		columns.clear();
		types.clear();
		comments.clear();
		isAutoIncrementKey = false;
		PreparedStatement pstate = conn.prepareStatement(showFields + table);
		ResultSet results = pstate.executeQuery();
		while (results.next()) {
			columns.add(results.getString("FIELD"));
			types.add(results.getString("TYPE"));
			comments.add(results.getString("COMMENT"));

			if("PRI".equals(results.getString("KEY"))){
				keyColumnName = results.getString("FIELD");
				keyColumnType = processType(results.getString("TYPE"));
				boolean isIntType = results.getString("TYPE").indexOf(type_int) > -1;
				boolean isAutoIncrement = "auto_increment".equals(results.getString("EXTRA"));
				if(isIntType && isAutoIncrement){
					isAutoIncrementKey = true;
				}
			}
		}
		initNameByTable(table);
		String tableComment = tableComments.get(table);
		buildEntityBean(columns, types, comments, tableComment);
		buildEntityDto(columns, types, comments, tableComment);
		buildMapper();
		buildMapperXml(columns, types, comments);
		buildServie();
		buildServieImpl();
	}


	/**
	 * 获取所有的表信息并循环生成相应文件
	 */
	public void generate() throws ClassNotFoundException, SQLException, IOException {
		initConnection();
		Map<String, String> tableComments = getTableComment();
		if (isNotEmpty(table_name)) {
			if(table_name.contains(",")){
				for (String table : table_name.split(",")) {
					generateByTable(tableComments, table);
				}
			}else {
				generateByTable(tableComments, table_name);
			}
		} else {
			List<String> tables = getTables();
			for (String table : tables) {
				generateByTable(tableComments, table);
			}
		}
		conn.close();
	}


	public static void main(String[] args) {
		try {
			Runtime runtime = Runtime.getRuntime();
			mkdirs(runtime);
			new EntityUtil().generate();
			// 自动打开生成文件的目录
			runtime.exec("cmd /c start explorer " + PACKAGE_PATH);
		} catch (ClassNotFoundException | SQLException | IOException e) {
			e.printStackTrace();
		}
	}
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值