Mysql数据库表生成java实体工具类

布满荆棘的人生 2022-05-16 05:09 703阅读 0赞
  1. import java.io.File;
  2. import java.io.FileWriter;
  3. import java.io.PrintWriter;
  4. import java.sql.Connection;
  5. import java.sql.DatabaseMetaData;
  6. import java.sql.DriverManager;
  7. import java.sql.PreparedStatement;
  8. import java.sql.ResultSet;
  9. import java.sql.ResultSetMetaData;
  10. import java.text.SimpleDateFormat;
  11. import java.util.ArrayList;
  12. import java.util.Date;
  13. import java.util.List;
  14. public class MysqlEntityUtil {
  15. private static final MysqlEntityUtil INSTANCE = new MysqlEntityUtil();
  16. private String tableName;// 表名
  17. private String[] colNames; // 列名数组
  18. private String[] colTypes; // 列名类型数组
  19. private int[] colSizes; // 列名大小数组
  20. private boolean needUtil = false; // 是否需要导入包java.util.*
  21. private boolean needSql = false; // 是否需要导入包java.sql.*
  22. private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  23. private static final String SQL = "SELECT * FROM ";// 数据库操作
  24. // TODO 需要修改的地方 jdbc:mysql://192.9.8.144:3306/wym_guotu_xc
  25. private static final String URL = "jdbc:mysql://192.9.8.144:3306/wym_guotu_xc";
  26. private static final String NAME = "root";
  27. private static final String PASS = "tj$123456";
  28. private static final String DRIVER = "com.mysql.jdbc.Driver";
  29. private String packageOutPath = "com.xc.test.entity.mysql";// 指定实体生成所在包的路径
  30. private String authorName = "xc";// 作者名字
  31. private String[] generateTables = null;//指定需要生成的表的表名,全部生成设置为null
  32. /**
  33. * 类的构造方法
  34. */
  35. private MysqlEntityUtil() {
  36. }
  37. /**
  38. * @return
  39. * @description 生成class的所有内容
  40. * @author paul
  41. * @date 2017年8月18日 下午5:30:07
  42. * @update 2017年8月18日 下午5:30:07
  43. * @version V1.0
  44. */
  45. private String parse() {
  46. StringBuffer sb = new StringBuffer();
  47. sb.append("package " + packageOutPath + ";\r\n");
  48. sb.append("\r\n");
  49. // 判断是否导入工具包
  50. if (needUtil) {
  51. sb.append("import java.util.Date;\r\n");
  52. }
  53. if (needSql) {
  54. sb.append("import java.sql.*;\r\n");
  55. }
  56. // 注释部分
  57. sb.append("/**\r\n");
  58. sb.append(" * table name: " + tableName + "\r\n");
  59. sb.append(" * author name: " + authorName + "\r\n");
  60. sb.append(" * create time: " + SDF.format(new Date()) + "\r\n");
  61. sb.append(" */ \r\n");
  62. // 实体部分
  63. sb.append("public class " + getTransStr(tableName, true) + "{\r\n\r\n");
  64. processAllAttrs(sb);// 属性
  65. sb.append("\r\n");
  66. processAllMethod(sb);// get set方法
  67. //processToString(sb);
  68. sb.append("}\r\n");
  69. return sb.toString();
  70. }
  71. /**
  72. * @param sb
  73. * @description 生成所有成员变量
  74. * @author paul
  75. * @date 2017年8月18日 下午5:15:04
  76. * @update 2017年8月18日 下午5:15:04
  77. * @version V1.0
  78. */
  79. private void processAllAttrs(StringBuffer sb) {
  80. for (int i = 0; i < colNames.length; i++) {
  81. sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + getTransStr(colNames[i], false) + ";\r\n");
  82. }
  83. }
  84. // /**
  85. // * 重写toString()方法
  86. // * @param sb
  87. // */
  88. // private void processToString(StringBuffer sb) {
  89. // sb.append("\t@Override\r\n\tpublic String toString() {\r\n");
  90. // sb.append("\t\treturn \"" +tableName + "{\" + \r\n");
  91. // for (int i = 0; i < colNames.length; i++) {
  92. // if (i != 0)
  93. // sb.append("\t\t\t\", ");
  94. // if (i == 0)
  95. // sb.append("\t\t\t\"");
  96. // sb.append(colNames[i] + "=\" + "
  97. // + colNames[i]).append(" + \r\n");
  98. // if (i == colNames.length - 1) {
  99. // sb.append("\t\t\t\"}\";\r\n");
  100. // }
  101. // }
  102. // sb.append("\t}\r\n");
  103. // }
  104. /**
  105. * @param sb
  106. * @description 生成所有get/set方法
  107. * @author paul
  108. * @date 2017年8月18日 下午5:14:47
  109. * @update 2017年8月18日 下午5:14:47
  110. * @version V1.0
  111. */
  112. private void processAllMethod(StringBuffer sb) {
  113. for (int i = 0; i < colNames.length; i++) {
  114. sb.append("\tpublic void set" + getTransStr(colNames[i], true) + "(" + sqlType2JavaType(colTypes[i]) + " "
  115. + getTransStr(colNames[i], false) + "){\r\n");
  116. sb.append("\t\tthis." + getTransStr(colNames[i], false) + "=" + getTransStr(colNames[i], false) + ";\r\n");
  117. sb.append("\t}\r\n");
  118. sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + getTransStr(colNames[i], true) + "(){\r\n");
  119. sb.append("\t\treturn " + getTransStr(colNames[i], false) + ";\r\n");
  120. sb.append("\t}\r\n");
  121. }
  122. }
  123. /**
  124. * @param str 传入字符串
  125. * @return
  126. * @description 将传入字符串的首字母转成大写
  127. * @author paul
  128. * @date 2017年8月18日 下午5:12:12
  129. * @update 2017年8月18日 下午5:12:12
  130. * @version V1.0
  131. */
  132. private String initCap(String str) {
  133. char[] ch = str.toCharArray();
  134. if (ch[0] >= 'a' && ch[0] <= 'z')
  135. ch[0] = (char) (ch[0] - 32);
  136. return new String(ch);
  137. }
  138. /**
  139. * @return
  140. * @description 将mysql中表名和字段名转换成驼峰形式
  141. * @author paul
  142. * @date 2017年8月18日 下午4:55:07
  143. * @update 2017年8月18日 下午4:55:07
  144. * @version V1.0
  145. */
  146. private String getTransStr(String before, boolean firstChar2Upper) {
  147. //不带"_"的字符串,则直接首字母大写后返回
  148. if (!before.contains("_"))
  149. return firstChar2Upper ? initCap(before) : before;
  150. String[] strs = before.split("_");
  151. StringBuffer after = null;
  152. if (firstChar2Upper) {
  153. after = new StringBuffer(initCap(strs[0]));
  154. } else {
  155. after = new StringBuffer(strs[0]);
  156. }
  157. if (strs.length > 1) {
  158. for (int i=1; i<strs.length; i++)
  159. after.append(initCap(strs[i]));
  160. }
  161. return after.toString();
  162. }
  163. /**
  164. * @return
  165. * @description 查找sql字段类型所对应的Java类型
  166. * @author paul
  167. * @date 2017年8月18日 下午4:55:41
  168. * @update 2017年8月18日 下午4:55:41
  169. * @version V1.0
  170. */
  171. private String sqlType2JavaType(String sqlType) {
  172. if (sqlType.equalsIgnoreCase("bit")) {
  173. return "boolean";
  174. } else if (sqlType.equalsIgnoreCase("tinyint")) {
  175. return "byte";
  176. } else if (sqlType.equalsIgnoreCase("smallint")) {
  177. return "short";
  178. } else if (sqlType.equalsIgnoreCase("int")) {
  179. return "int";
  180. } else if (sqlType.equalsIgnoreCase("bigint")) {
  181. return "long";
  182. } else if (sqlType.equalsIgnoreCase("float")) {
  183. return "float";
  184. } else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
  185. || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
  186. || sqlType.equalsIgnoreCase("smallmoney")) {
  187. return "double";
  188. } else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
  189. || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
  190. || sqlType.equalsIgnoreCase("text")) {
  191. return "String";
  192. } else if (sqlType.equalsIgnoreCase("datetime")) {
  193. return "Date";
  194. } else if (sqlType.equalsIgnoreCase("image")) {
  195. return "Blod";
  196. }
  197. return null;
  198. }
  199. /**
  200. *
  201. * @description 生成方法
  202. * @author paul
  203. * @date 2017年8月18日 下午2:04:20
  204. * @update 2017年8月18日 下午2:04:20
  205. * @version V1.0
  206. * @throws Exception
  207. */
  208. private void generate() throws Exception {
  209. //与数据库的连接
  210. Connection con;
  211. PreparedStatement pStemt = null;
  212. Class.forName(DRIVER);
  213. con = DriverManager.getConnection(URL, NAME, PASS);
  214. System.out.println("connect database success...");
  215. //获取数据库的元数据
  216. DatabaseMetaData db = con.getMetaData();
  217. //是否有指定生成表,有指定则直接用指定表,没有则全表生成
  218. List<String> tableNames = new ArrayList<>();
  219. if (generateTables == null) {
  220. //从元数据中获取到所有的表名
  221. ResultSet rs = db.getTables(null, null, null, new String[] { "TABLE" });
  222. while (rs.next()) tableNames.add(rs.getString(3));
  223. } else {
  224. for (String tableName : generateTables) tableNames.add(tableName);
  225. }
  226. String tableSql;
  227. PrintWriter pw = null;
  228. for (int j = 0; j < tableNames.size(); j++) {
  229. tableName = tableNames.get(j);
  230. tableSql = SQL + tableName;
  231. pStemt = con.prepareStatement(tableSql);
  232. ResultSetMetaData rsmd = pStemt.getMetaData();
  233. int size = rsmd.getColumnCount();
  234. colNames = new String[size];
  235. colTypes = new String[size];
  236. colSizes = new int[size];
  237. //获取所需的信息
  238. for (int i = 0; i < size; i++) {
  239. colNames[i] = rsmd.getColumnName(i + 1);
  240. colTypes[i] = rsmd.getColumnTypeName(i + 1);
  241. if (colTypes[i].equalsIgnoreCase("datetime"))
  242. needUtil = true;
  243. if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text"))
  244. needSql = true;
  245. colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
  246. }
  247. //解析生成class的所有内容
  248. String content = parse();
  249. //输出生成文件
  250. File directory = new File("");
  251. String dirName = directory.getAbsolutePath() + "/src/main/java/" + packageOutPath.replace(".", "/");
  252. File dir = new File(dirName);
  253. if (!dir.exists() && dir.mkdirs()) System.out.println("generate dir 【" + dirName + "】");
  254. String javaPath = dirName + "/" + getTransStr(tableName, true) + ".java";
  255. FileWriter fw = new FileWriter(javaPath);
  256. pw = new PrintWriter(fw);
  257. pw.println(content);
  258. pw.flush();
  259. System.out.println("create class 【" + tableName + "】");
  260. }
  261. if (pw != null)
  262. pw.close();
  263. }
  264. /**
  265. * @param args
  266. * @description 执行方法
  267. * @author paul
  268. * @date 2017年8月18日 下午2:03:35
  269. * @update 2017年8月18日 下午2:03:35
  270. * @version V1.0
  271. */
  272. public static void main(String[] args) {
  273. try {
  274. INSTANCE.generate();
  275. System.out.println("generate classes success!");
  276. } catch (Exception e) {
  277. e.printStackTrace();
  278. }
  279. }

发表评论

表情:
评论列表 (有 0 条评论,703人围观)

还没有评论,来说两句吧...

相关阅读