java创建实体类(get/set方法链式调用)

1.自动获取数据库表,创建实体类

/**
 * 自动获取数据库表,创建实体类
 * @since 2020.03.12
 * @author qin_myu
 */
public class DomainAutoCreate {
	private String tablename = "TABLE_NAME";// 表名
	private String packagename = "com.qmy.domain;";// 输出包名
	private String classname = "Domain";// 输出实体类名
	private String[] colnames; // 字段数组
	private String[] colTypes; // 字段类型数组
	private int[] colSizes; // 列名大小数组
	private boolean f_util = false; // 是否需要导入包java.util.*
	private boolean f_math = false;// 是否需要导入包java.math.*

	public static void main(String[] args) {
		new DomainAutoCreate();
	}

	public DomainAutoCreate() {
		Connection conn = DBUtil.getConnection();// 建立数据库连接
		PreparedStatement ps = null;
		ResultSetMetaData rs = null;
		String strsql = "SELECT * FROM " + tablename;
		try {
			ps = conn.prepareStatement(strsql);
			// ResultSet获取结果集
			ResultSet rs2 = ps.executeQuery();
			// ResultSetMetaData获取表字段及属性
			rs = rs2.getMetaData();
			int size = rs.getColumnCount();
			colnames = new String[size];
			colTypes = new String[size];
			colSizes = new int[size];
			for (int i = 0; i < rs.getColumnCount(); i++) {
				colnames[i] = rs.getColumnName(i + 1).toLowerCase();
				colTypes[i] = rs.getColumnTypeName(i + 1).toUpperCase();
				if (colTypes[i].equalsIgnoreCase("DATETIME") || colTypes[i].equalsIgnoreCase("DATE")
						|| colTypes[i].equalsIgnoreCase("SMALLDATETIME") || colTypes[i].equalsIgnoreCase("TIME")) {
					f_util = true;
				}
				if (colTypes[i].equalsIgnoreCase("MONEY") || colTypes[i].equalsIgnoreCase("DECIMAL")
						|| colTypes[i].equalsIgnoreCase("SMALLMONEY") || colTypes[i].equalsIgnoreCase("NUMERIC")) {
					f_math = true;
				}
				colSizes[i] = rs.getColumnDisplaySize(i + 1);
			}
			String content = parse(colnames, colTypes, colSizes, packagename);
			FileWriter fileWriter = new FileWriter(initcap(tablename.toLowerCase()) + ".java");
			PrintWriter pw = new PrintWriter(fileWriter);
			pw.println(content);
			pw.flush();
			pw.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				ps.close();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	/**
	 * 解析处理(生成实体类主体代码)
	 * 
	 * @param colNames
	 * @param colTypes
	 * @param colSizes
	 * @param packagename
	 * @return
	 */
	private String parse(String[] colNames, String[] colTypes, int[] colSizes, String packagename) {
		StringBuffer sb = new StringBuffer();
		// 导入包
		sb.append("package " + packagename + "\r\n\n");
		if (f_util) {
			sb.append("import java.util.Date;\r\n\n");
		}
		if (f_math) {
			sb.append("import java.math.BigDecimal;\r\n\n");
		}
		sb.append("public class " + initcap(classname) + " {\r\n");

		for (int i = 0; i < colnames.length; i++) {
			sb.append("\tprivate " + sqlTypeToJavaType(colTypes[i]) + " " + colnames[i] + ";\r\n");
		}
		sb.append("\n\n");
		// 生成get/set方法(链式调用)
		for (int i = 0; i < colnames.length; i++) {
			// get 方法
			sb.append("\tpublic " + sqlTypeToJavaType(colTypes[i]) + " get" + initcap(colnames[i]) + "(){\r\n");
			sb.append("\t\treturn " + colnames[i] + ";\r\n");
			sb.append("\t}\r\n");

			// set 方法
			sb.append("\tpublic " + initcap(classname) + " set" + initcap(colnames[i]) + "("
					+ sqlTypeToJavaType(colTypes[i]) + " " + colnames[i] + "){\r\n");
			sb.append("\t\tthis." + colnames[i] + "=" + colnames[i] + ";\r\n");
			sb.append("\t\treturn this;\r\n");
			sb.append("\t}\r\n");
		}
		sb.append("}\r\n");
		System.out.println(sb.toString());
		return sb.toString();
	}

	/**
	 * 判断数据库字段类型转换为实体类对应函数类型
	 * @param sqlType
	 * @return
	 */
	private String sqlTypeToJavaType(String sqlType) {
		if (sqlType.equalsIgnoreCase("BIT")) {
			return "Boolean";
		} else if (sqlType.equalsIgnoreCase("BINARY") || sqlType.equalsIgnoreCase("IMAGE")
				|| sqlType.equalsIgnoreCase("VARBINARY")) {
			return "byte[]";
		} else if (sqlType.equalsIgnoreCase("SMALLINT") || sqlType.equalsIgnoreCase("TINYINT")) {
			return "short";
		} else if (sqlType.equalsIgnoreCase("INT") || sqlType.equalsIgnoreCase("INTEGER")) {
			return "int";
		} else if (sqlType.equalsIgnoreCase("BIGINT")) {
			return "long";
		} else if (sqlType.equalsIgnoreCase("REAL")) {
			return "float";
		} else if (sqlType.equalsIgnoreCase("REAL") || sqlType.equalsIgnoreCase("FLOAT")
				|| sqlType.equalsIgnoreCase("NUMBER")) {
			return "double";
		} else if (sqlType.equalsIgnoreCase("DECIMAL") || sqlType.equalsIgnoreCase("SMALLMONEY")
				|| sqlType.equalsIgnoreCase("NUMERIC")) {
			return "BigDecimal";
		} else if (sqlType.equalsIgnoreCase("VARCHAR") || sqlType.equalsIgnoreCase("VARCHAR2")
				|| sqlType.equalsIgnoreCase("CHAR") || sqlType.equalsIgnoreCase("NVARCHAR")
				|| sqlType.equalsIgnoreCase("NCHAR") || sqlType.equalsIgnoreCase("TEXT")
				|| sqlType.equalsIgnoreCase("NTEXT") || sqlType.equalsIgnoreCase("UNIQUEIDENTIFIER")) {
			return "String";
		} else if (sqlType.equalsIgnoreCase("DATE") || sqlType.equalsIgnoreCase("TIMESTAMP")) {
			return "DATE";// Date
		} else if (sqlType.equalsIgnoreCase("SMALLDATETIME") || sqlType.equalsIgnoreCase("DATETIME")) {
			return "Timestamp";
		} else if (sqlType.equalsIgnoreCase("TIME")) {
			return "Time";
		}
		return null;
	}

	/**
	 * 把输入字符串的首字母改成大写
	 * @param str
	 * @return
	 */
	private static String initcap(String str) {
		char[] ch = str.toCharArray();
		if (ch[0] >= 'a' && ch[0] <= 'z') {
			ch[0] = (char) (ch[0] - 32);
		}
		return new String(ch);
	}
}

2.java自定义输出实体类

/**
 * 自定义字段创建实体类
 * @since 2020.03.12
 * @author qin_myu
 */
public class DomainCreate {

	private static String packageName = "com.qmy.domain;";// 输出包名
	private static String domainPO = "Domain";// 实体类名
	private static String column = "a,b,c,d";// 字段
	private static String columnType = "String,Date,Double,int";// 字段类型
	private static String columnNotes = "a,b,c,d";// 字段注释
	private static String classNotes = "xxxxxxx";// 类注释
	
	public static void main(String[] args) {
		String[] columns = column.split(",");
		String[] notes = columnNotes.split(",");
		String[] columnTypes = columnType.split(",");
		
		
		StringBuffer sb = new StringBuffer();
		// 包名
		sb.append("package " + packageName + "\r\n\n\n");
		
		// 实体类注释
		sb.append("/*"+classNotes+"*/\r\n");
		sb.append("public class " + domainPO + " {\r\n");
		for (int i = 0; i < columns.length; i++) {
			sb.append("\t// " + notes[i] + "\r\n");
			sb.append("\tprivate "+columnTypes[i] +" "+ columns[i] + ";\r\n");
		}

		sb.append("\n\n");
		for (int i = 0; i < columns.length; i++) {
			// get方法
			sb.append("\tpublic "+columnTypes[i] +" get" + initcap(columns[i]) + "(){\r\n");
			sb.append("\t\treturn " + columns[i] + ";\r\n");
			sb.append("\t}\r\n");
			// set方法(链式调用)
			sb.append("\tpublic " + domainPO + " set" + initcap(columns[i]) + "(String " + columns[i] + "){\r\n");
			sb.append("\t\tthis." + columns[i] + "=" + columns[i] + ";\r\n");
			sb.append("\t\treturn this;\r\n");
			sb.append("\t}\r\n");
		}
		sb.append("}\r\n");
		System.out.println(sb.toString());
	}

	/**
	 * 把输入字符串的首字母改成大写
	 * @param str
	 * @return
	 */
	private static String initcap(String str) {
		char[] ch = str.toCharArray();
		if (ch[0] >= 'a' && ch[0] <= 'z') {
			ch[0] = (char) (ch[0] - 32);
		}
		return new String(ch);
	}
}

数据库连接工具类

/**
 * 建立数据库连接工具类
 * @since 2020.03.12
 * @author qin_myu
 */
public class DBUtil {
	// 驱动,服务器地址,登录用户名,密码
	static String DRIVER;
	static String DATEBASEURL;
	static String USERNAME;
	static String PASSWORD;
	
	// Connection连接对象
	static Connection conn = null;
	// Statement命令对象
	static Statement stmt = null;
	static PreparedStatement pstmt = null;

	static {
		/* DB2数据库 */
		// DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		// DATEBASEURL
		// ="jdbc:sqlserver://localhost:1433;databasename=YerGoMallPro";
		// USERNAME = "sa";// DBPWD = "@zdm168168...";
		// PASSWORD = "123456";// 打开连接

		/* ORACLE数据库 */
		DRIVER = "oracle.jdbc.driver.OracleDriver";
		DATEBASEURL = "jdbc:oracle:thin:@localhost:1521/orcl";
		USERNAME = "admin";
		PASSWORD = "admin";

		/* SQLServer数据库 */
		// DRIVER= "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		// DATEBASEURL= "jdbc:sqlserver://localhost:1433;DateBaseName=数据库名";
		// USERNAME = "sa";
		// PASSWORD = "sa";

		/* MySQL数据库 */
		// DRIVER="com.mysql.jdbc.Driver";
		// USERNAME="root";
		// PASSWORD="root";
		// DATEBASEURL = "jdbc:mysql://localhost/test?user=" + USERNAME +
		// "&password=" + PASSWORD+ "&useUnicode=true&characterEncoding=UTF-8";
	}
	// 通过本方法获得连接对象
		public static Connection getConnection() {
			try {
				if (conn == null || conn.isClosed())
					open();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return conn;
		}
	/**
	 * 建立连接对象(打开连接)
	 */
	public static void open() {
		try {
			// 加载驱动
			Class.forName(DRIVER);
			conn = DriverManager.getConnection(DATEBASEURL, USERNAME, PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 关闭连接
	 */
	public static void close() {
		try {
			if (stmt != null)
				stmt.close();
			if (conn != null && !conn.isClosed())
				conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	

	// executeQuery
	// executeUpdate
	// execute
	// 获得查询的数据集
	// select * from student where name='' and sex=''
	public static ResultSet executeQuery(String sql) {
		try {
			open();// 保证连接是成功的
			stmt = conn.createStatement();
			return stmt.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// 修改表格内容
	public static int executeUpdate(String sql) {
		int result = 0;
		try {
			open();// 保证连接是成功的
			stmt = conn.createStatement();
			result = stmt.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			close();
		}
		return result;
	}

	// 如果执行的查询或存储过程,会返回多个数据集,或多个执行成功记录数
	// 可以调用本方法,返回的结果,
	// 是一个List或List集合
	public static Object execute(String sql) {
		boolean b = false;
		try {
			open();// 保证连接是成功的
			stmt = conn.createStatement();
			b = stmt.execute(sql);
			// true,执行的是一个查询语句,我们可以得到一个数据集
			// false,执行的是一个修改语句,我们可以得到一个执行成功的记录数
			if (b) {
				return stmt.getResultSet();
			} else {
				return stmt.getUpdateCount();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (!b) {
				close();
			}
		}
		return null;
	}

	//
	// select * from student where name=? and sex=?
	public static ResultSet executeQuery(String sql, Object[] in) {
		try {
			open();// 保证连接是成功的
			PreparedStatement pst = conn.prepareStatement(sql);
			for (int i = 0; i < in.length; i++)
				pst.setObject(i + 1, in[i]);
			stmt = pst;// 只是为了关闭命令对象pst
			return pst.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static int executeUpdate(String sql, Object[] in) {
		try {
			open();// 保证连接是成功的
			PreparedStatement pst = conn.prepareStatement(sql);
			for (int i = 0; i < in.length; i++)
				pst.setObject(i + 1, in[i]);
			stmt = pst;// 只是为了关闭命令对象pst
			return pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			close();
		}
		return 0;
	}

	public static PreparedStatement pstmt(String sql) {
		open();
		try {
			return pstmt = conn.prepareStatement(sql);
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return null;
	}

	public static Object execute(String sql, Object[] in) {
		boolean b = false;
		try {
			open();// 保证连接是成功的
			PreparedStatement pst = conn.prepareStatement(sql);
			for (int i = 0; i < in.length; i++)
				pst.setObject(i + 1, in[i]);
			b = pst.execute();
			// true,执行的是一个查询语句,我们可以得到一个数据集
			// false,执行的是一个修改语句,我们可以得到一个执行成功的记录数
			if (b) {
				System.out.println("----");
				/*
				 * List list = new ArrayList();
				 * list.add(pst.getResultSet()); while(pst.getMoreResults()) {
				 * list.add(pst.getResultSet()); }
				 */
				return pst.getResultSet();
			} else {
				System.out.println("****");
				List<Integer> list = new ArrayList<Integer>();
				list.add(pst.getUpdateCount());
				while (pst.getMoreResults()) {
					list.add(pst.getUpdateCount());
				}
				return list;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (!b) {
				System.out.println("====");
				close();
			}
		}
		return null;
	}

	// 调用存储过程 proc_Insert(?,?,?)
	public static Object executeProcedure(String procName, Object[] in) {
		open();
		try {
			procName = "{call " + procName + "(";
			String link = "";
			for (int i = 0; i < in.length; i++) {
				procName += link + "?";
				link = ",";
			}
			procName += ")}";
			CallableStatement cstmt = conn.prepareCall(procName);
			for (int i = 0; i < in.length; i++) {
				cstmt.setObject(i + 1, in[i]);
			}
			if (cstmt.execute()) {
				return cstmt.getResultSet();
			} else {
				return cstmt.getUpdateCount();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	/*
	 * 调用存储过程,并有输出参数
	 * 
	 * @procName ,存储过程名称:proc_Insert(?,?)
	 * 
	 * @in ,输入参数集合
	 * 
	 * @output,输出参数集合
	 * 
	 * @type,输出参数类型集合
	 */
	public static Object executeOutputProcedure(String procName, Object[] in, Object[] output, int[] type) {
		Object result = null;
		try {
			CallableStatement cstmt = conn.prepareCall("{call " + procName + "}");
			// 设置存储过程的参数值
			int i = 0;
			for (; i < in.length; i++) {// 设置输入参数
				cstmt.setObject(i + 1, in[i]);
				// print(i+1);
			}
			int len = output.length + i;
			for (; i < len; i++) {// 设置输出参数
				cstmt.registerOutParameter(i + 1, type[i - in.length]);
				// print(i+1);
			}
			boolean b = cstmt.execute();
			// 获取输出参数的值
			for (i = in.length; i < output.length + in.length; i++)
				output[i - in.length] = cstmt.getObject(i + 1);
			if (b) {
				result = cstmt.getResultSet();
			} else {
				result = cstmt.getUpdateCount();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	// 时间转换
	public static Date date(String date_str) {
		try {
			Calendar cal = Calendar.getInstance();// 日期类
			Timestamp timestampnow = new Timestamp(cal.getTimeInMillis());// 转换成正常的日期格式
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");// 改为需要的东西
			ParsePosition pos = new ParsePosition(0);
			java.util.Date current = formatter.parse(date_str, pos);
			timestampnow = new Timestamp(current.getTime());
			return timestampnow;
		} catch (NullPointerException e) {
			return null;
		}
	}

}

你可能感兴趣的:(java创建实体类(get/set方法链式调用))