这是一个整理出来的JAVA工具类,用于将MySQL数据库表生成Entity实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package com.nmore.smile.utils;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName: GenEntity
* @Description: 数据库表生成Entity工具类
* @Author devfzm@gmail.com
* @Date 2016年2月29日 上午10:13:36
*
*/
public class GenEntity {
//输出到自定义目录,为空代表输出到当前目录
private static final String PATH = "";
//包名(当指定PATH时,请同步修改PACKAGE,为空则默认为当前目录),如:com.nmore.smile.entity
private static String PACKAGE = "";
true
//数据库连接
private static final String DATABASE = "imall";
private static final String URL ="jdbc:mysql://localhost:3306/"+ DATABASE +"?useUnicode=true&characterEncoding=UTF8&useSSL=false";
private static final String NAME = "root";
private static final String PASS = "123456";
private static final String DRIVER ="com.mysql.jdbc.Driver";
//用于生成实体
private String[] colnames; //列名数组
private String[] colTypes; //列名类型数组
private boolean f_util = false; //是否需要导入包java.util.*
//用于查询表的列详情,并读取生成注释
private Statement stm;
private ResultSet rs;
//数据库连接
private Connection con;
/**
* 构造函数
*/
public GenEntity(){
//创建数据库连接
con = connectionDB();
try {
/**
* 以下提供两种生成方法,使用其中一种请注释另一种
*/
//①此处可以自定定义需要生成的实体类表名,数组形式
String[] arr = new String[]{"attr_name", "attr_value"};
for(String str : arr){
//开始生成实体类
this.init(str, null);
}
//②initAll,将数据库中所有表都生成[***Entity.java]
//this.initAll();
} catch (Exception e){
e.printStackTrace();
} finally {
try {
//关闭数据库连接
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* @Title: main
* @param args
* @return void
*/
public static void main(String[] args) {
System.out.println("Init..");
new GenEntity();
System.out.println("Init Complete..");
}
/**
* @param tablename 表名
* @param notes 注释,该参数为缺省字段,null就会去查询
* @return
*/
@SuppressWarnings("unused")
public void init(String tablename, String notes){
try {
//查询要生成实体类的表
String sql = "show full columns from `" + tablename + "`";
//执行查询,并获取结果
stm = con.createStatement();
rs = stm.executeQuery(sql);
//统计行数,一行就是一个字段
rs.last();//移到最后一行
int size = rs.getRow();
rs.beforeFirst();//如果还要用结果集,就把指针再移到初始化的位置
colnames = new String[size];
colTypes = new String[size];
//读取查询的结果集
int i = 0;
while(rs.next()){
//将列名和对应数据类型存入数组
colnames[i] = rs.getString("Field");
colTypes[i] = rs.getString("Type").replaceAll("[(].*[)]", "");
//判断数据类型是否需要引入Util
if(colTypes[i].equalsIgnoreCase("datetime")) f_util = true;
i++;
}
//判断是否传递了注释,没有就去查询
if(notes == null){
notes = this.queryTableNotes(tablename).toString();
}
//拼装实体类内容
String content = parse(colnames, colTypes, tablename, notes);
try {
File directory = new File("");
String path = this.getClass().getResource("").getPath();
//设置文件输出路径
if(PATH == ""){
path = directory.getAbsolutePath() + "\\src\\main\\java\\" + path.substring(path.lastIndexOf("com/", path.length()), path.length()).replace("/", "\\");
}else{
path = PATH;
}
//文件写入
FileWriter fw = new FileWriter(path + initcap(tablename) + "Entity.java");
PrintWriter pw = new PrintWriter(fw);
pw.println(content);
pw.flush();
pw.close();
} catch (Exception ex){
ex.printStackTrace();
}
} catch (Exception e){
e.printStackTrace();
}
}
/**
* @Title: initAll
* @Description: 初始化生成所有数据库表对应的Entity
* @return void
* @throws
*/
@SuppressWarnings("unchecked")
public void initAll(){
//查询所有表表名和注释
Map<String, String> table_notes = (Map<String, String>) queryTableNotes(null);
//非空校验
if(table_notes != null){
for (Map.Entry<String, String> entry : table_notes.entrySet()) {
//开始生成实体类
this.init(entry.getKey(), entry.getValue());
}
}
}
true
/**
* 功能:生成实体类主体代码
* @param colnames
* @param colTypes
* @param colSizes
* @param tablename 表名
* @return 实体类主体代码字符串
* @throws SQLException
*/
private String parse(String[] colnames, String[] colTypes, String tablename, String notes) throws SQLException {
String entity = initcap(tablename);
StringBuffer sb = new StringBuffer();
String path = this.getClass().getResource("").getPath();
//获取包名
PACKAGE = PACKAGE != ""?PACKAGE:path.substring(path.lastIndexOf("com/", path.length()), path.length()-1).replace("/", ".");
//写入包名和依赖类
sb.append("package "+ PACKAGE +";\r\n\r\n");
sb.append("import com.nmore.smile.base.BaseEntity;\r\n");
//判断是否导入工具包
if(f_util){
sb.append("import java.util.Date;\r\n");
f_util = false;
}
sb.append("\r\n");
//注释部分
sb.append("/**\r\n");
sb.append("* @ClassName: "+ entity +" \r\n");
sb.append("* @Description: "+ notes +" \r\n");
sb.append("* @Author devfzm@gmail.com \r\n");
sb.append("* @Date "+ new Date() +" \r\n");
sb.append("*/\r\n");
//实体部分
sb.append("\r\n@SuppressWarnings(\"serial\")\r\npublic class " + initcap(tablename) + "Entity extends BaseEntity {\r\n");
processAllAttrs(sb);//属性
processAllMethod(sb);//get set方法
sb.append("}\r\n");
return sb.toString();
}
/**
* 功能:生成所有属性和对应注释
* @param sb
* @throws SQLException
*/
private void processAllAttrs(StringBuffer sb) throws SQLException {
int i = 0;
rs.beforeFirst();//如果还要用结果集,就把指针再移到初始化的位置
while(rs.next()) {
sb.append("\t//" + rs.getString("Comment"));
sb.append("\n\tprivate " + sqlType2JavaType(colTypes[i]) + " " + colnames[i] + ";\r\n");
i++;
}
sb.append("\r\n");
rs.close();
stm.close();
}
/**
* 功能:生成所有 Getter/Setter 方法
* @param sb
*/
private void processAllMethod(StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
sb.append("\tpublic void set" + initcap(colnames[i]) + "(" + sqlType2JavaType(colTypes[i]) + " " +
colnames[i] + "){\r\n");
sb.append("\t\tthis." + colnames[i] + "=" + colnames[i] + ";\r\n");
sb.append("\t}\r\n");
sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(colnames[i]) + "(){\r\n");
sb.append("\t\treturn " + colnames[i] + ";\r\n");
sb.append("\t}\r\n");
}
}
/**
* 功能:获得列的数据类型
* @param sqlType
* @return javaType
*/
private String sqlType2JavaType(String sqlType) {
if(sqlType.equalsIgnoreCase("bit")){
return "Boolean";
}else if(sqlType.equalsIgnoreCase("tinyint")){
return "byte";
}else if(sqlType.equalsIgnoreCase("smallint")){
return "short";
}else if(sqlType.equalsIgnoreCase("int")){
return "Integer";
}else if(sqlType.equalsIgnoreCase("bigint")){
return "long";
}else if(sqlType.equalsIgnoreCase("float")){
return "float";
}else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
|| sqlType.equalsIgnoreCase("smallmoney")){
return "Double";
}else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
|| sqlType.equalsIgnoreCase("text")){
return "String";
}else if(sqlType.equalsIgnoreCase("datetime")){
return "Date";
}else if(sqlType.equalsIgnoreCase("image")){
return "Blod";
}
return null;
}
/**
* 功能:将输入字符串的首字母和"_a"格式的字母改成大写
* @param str
* @return
*/
private 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);
}
/**
* @Title: queryTableNotes
* @Description: 查询表注释
* @param tableName 该参数为缺省参数,不传默认查询所有表
* @return Object
* @throws
*/
public Object queryTableNotes(String tableName){
try {
//查询表名称和注释,默认查询数据库的全部表(即tableName为null时)
String sql = "select table_name,table_comment from information_schema.`TABLES` WHERE table_schema = '"+ DATABASE +"'";
if(tableName != null){
sql += " and table_name='"+ tableName +"'";
}
//执行查询,并获取结果
Statement sta = con.createStatement();
ResultSet rst = sta.executeQuery(sql);
//读取查询结果
if(tableName != null){
String str = "";
while(rst.next()){
str = rst.getString("table_comment");
}
sta.close();
rst.close();
return str;
}else{
Map<String, String> map = new HashMap<String, String>();
while(rst.next()){
map.put(rst.getString("table_name"), rst.getString("table_comment"));
}
sta.close();
rst.close();
return map;
}
} catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 建立数据的连接
* @exception SQLException, ClassNotFoundException
*/
public Connection connectionDB(){
try{
Class.forName(DRIVER);
Connection conn = DriverManager.getConnection(URL, NAME, PASS);
//System.out.println("连接数据库成功");
return conn;
}catch(Exception e){
e.printStackTrace();
//System.out.println("建立数据库发生错误!");
return null;
}
}
}