本周学习内容:
1.目录结构如图:
2.bean包下的类源码
1)字段类 ColumnInfo:
package main.com.oxx.sorm.bean;
/**
* 表中字段的信息
*/
public class ColumnInfo {
/**
* 字段名称
*/
private String name;
/**
* 字段类型
*/
private String dataType;
/**
* 字段键类型 (0,普通键 1.主键 2.外键)
*/
private int keyType;
public ColumnInfo() {
}
public ColumnInfo(String name, String dataType, int keyType) {
this.name = name;
this.dataType = dataType;
this.keyType = keyType;
}
/**在此省略get set 方法**/
}
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
2)表信息TableInfo:
1
package main.com.oxx.sorm.bean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 存储表结构信息
*/
public class TableInfo {
/**
* 表名
*/
private String tname;
/**
* 所有字段信息
*/
private Map<String, ColumnInfo> columns;
private ColumnInfo onlyPriKey;
private List<ColumnInfo> listPriKey;
public List<ColumnInfo> getListPriKey() {
return listPriKey;
}
public void setListPriKey(List<ColumnInfo> listPriKey) {
this.listPriKey = listPriKey;
}
public TableInfo() {
}
public TableInfo(String tname, Map<String, ColumnInfo> columns, ColumnInfo onlyPriKey) {
this.tname = tname;
this.columns = columns;
this.onlyPriKey = onlyPriKey;
}
public TableInfo(String tableName, ArrayList<ColumnInfo> columnInfos, HashMap<String, ColumnInfo> columnsMap) {
this.tname = tableName;
this.listPriKey = columnInfos;
this.columns = columnsMap;
}
/**在此省略get set 方法**/
}
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
3)配置信息类Configuration:
1
package main.com.oxx.sorm.bean;
/**
* 管理配置信息
*/
public class Configuration {
private String driver;
private String url;
private String user;
private String pwd;
private String usingDB;
private String srcPath;
private String poPackage;
private String queryClass;
/**在此省略get set 方法**/
public Configuration() {
}
public Configuration(String driver, String url, String user, String pwd, String usingDB, String srcPath, String poPackage, String queryClass) {
this.driver = driver;
this.url = url;
this.user = user;
this.pwd = pwd;
this.usingDB = usingDB;
this.srcPath = srcPath;
this.poPackage = poPackage;
this.queryClass = queryClass;
}
}
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
4)属性,get,set方法存储类 JavaFieldGetSet:
1
package main.com.oxx.sorm.bean;
public class JavaFieldGetSet {
private String fieldInfo;
private String getInfo;
private String setInfo;
public JavaFieldGetSet() {
}
public JavaFieldGetSet(String fieldInfo, String getInfo, String setInfo) {
this.fieldInfo = fieldInfo;
this.getInfo = getInfo;
this.setInfo = setInfo;
}
/**在此省略get set 方法**/
@Override
public String toString() {
System.out.println(fieldInfo);
System.out.println(getInfo);
System.out.println(setInfo);
return super.toString();
}
}
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
2.core包下的核心类:
1)读取配置文件类DBManager:
package main.com.oxx.sorm.core;
import main.com.oxx.sorm.bean.Configuration;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
/**
* 根据数据库连接 维持对象的管理
*/
public class DBManager {
private static Configuration configuration;
static{
Properties prop = new Properties();
try {
prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(“db.properties”));
} catch (IOException e) {
e.printStackTrace();
}
configuration = new Configuration();
configuration.setDriver(prop.getProperty(“driver”));
configuration.setUrl(prop.getProperty(“url”));
configuration.setUser(prop.getProperty(“user”));
configuration.setPwd((prop.getProperty(“pwd”)));
configuration.setSrcPath(prop.getProperty(“srcPath”));
configuration.setUsingDB(prop.getProperty(“usingDB”));
configuration.setPoPackage(prop.getProperty(“poPackage”));
configuration.setQueryClass(prop.getProperty(“queryClass”));
}
public static Connection getConn(){
try {
Class.forName(configuration.getDriver());
return DriverManager.getConnection(configuration.getUrl(), configuration.getUser(), configuration.getPwd());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Configuration getConfiguration(){
return configuration;
}
}
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
2)生成类文件 TableContext:
1
package main.com.oxx.sorm.core;
import main.com.oxx.sorm.bean.ColumnInfo;
import main.com.oxx.sorm.bean.TableInfo;
import main.com.oxx.sorm.util.StringUtil;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static main.com.oxx.sorm.util.JavaFileUtils.createJavaPOFile;
/**
* 负责管理数据库表结构与类的关系
*/
public class TableContext {
//表名与表信息
private static Map<String, TableInfo> tables = new HashMap<String, TableInfo>();
//po的class对象与表信息
private static Map<Class, TableInfo> poClassTableMap = new HashMap<Class, TableInfo>();
static{
Connection conn = DBManager.getConn();
try {
DatabaseMetaData databaseMetaData = conn.getMetaData();
ResultSet tableSet = databaseMetaData.getTables(null, “%”, “%”, new String[]{“TABLE”});
while(tableSet.next()){
String tableName = (String)tableSet.getObject(“TABLE_NAME”);
TableInfo tableInfo = new TableInfo(tableName, new ArrayList<ColumnInfo>(), new HashMap<String, ColumnInfo>());
tables.put(tableName, tableInfo);
ResultSet columnSet = databaseMetaData.getColumns(null, “%”, tableName, “%”);
while(columnSet.next()){
ColumnInfo columnInfo = new ColumnInfo(columnSet.getString(“COLUMN_NAME”),
columnSet.getString(“TYPE_NAME”), 0);
tableInfo.getColumns().put(columnSet.getString(“COLUMN_NAME”), columnInfo);
}
ResultSet keySet = databaseMetaData.getPrimaryKeys(null, “%”, tableName);
while(keySet.next()){
ColumnInfo columnInfo2 = tableInfo.getColumns().get(keySet.getObject(“COLUMN_NAME”));
columnInfo2.setKeyType(1);
tableInfo.getListPriKey().add(columnInfo2);
}
if(tableInfo.getListPriKey().size() > 0){
tableInfo.setOnlyPriKey(tableInfo.getListPriKey().get(0));
}
}
} catch (Exception e) {
e.printStackTrace();
}
//更新po类文件
updateJavaPoFile();
//加载class类
loadPOTable();
}
public static Map<String, TableInfo> getTableInfo(){
return tables;
}
public static void updateJavaPoFile(){
Map<String, TableInfo> tableMap = TableContext.getTableInfo();
for(TableInfo table : tableMap.values()){
createJavaPOFile(table, new MySqlTypeConvertor());
}
}
public static Map<String, TableInfo> getTables() {
return tables;
}
public static void setTables(Map<String, TableInfo> tables) {
TableContext.tables = tables;
}
public static Map<Class, TableInfo> getPoClassTableMap() {
return poClassTableMap;
}
public static void setPoClassTableMap(Map<Class, TableInfo> poClassTableMap) {
TableContext.poClassTableMap = poClassTableMap;
}
public static void loadPOTable(){
for(TableInfo tableInfo : tables.values()){
try {
Class clazz = Class.forName(DBManager.getConfiguration().getPoPackage() + “.” +StringUtil.firstChar2UpperCase(tableInfo.getTname()));
poClassTableMap.put(clazz, tableInfo);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
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
3)Query工厂:
1
package main.com.oxx.sorm.core;
public class QueryFactory {
private static Query query;
private QueryFactory(){}
static{
try {
Class clazz = Class.forName(DBManager.getConfiguration().getQueryClass());
query = (Query)clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
//在此使用模板方法 当然也可以使用 newInstance的方式
public static Query createQuery() throws CloneNotSupportedException {
return (Query)query.clone();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
4)Query抽象类
1
package main.com.oxx.sorm.core;
import main.com.oxx.sorm.bean.ColumnInfo;
import main.com.oxx.sorm.bean.TableInfo;
import main.com.oxx.sorm.util.JDBCUtil;
import main.com.oxx.sorm.util.ReflectUtil;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public abstract class Query implements Cloneable{
public int executeDML(String sql, Object[] params) {
Connection conn = DBManager.getConn();
PreparedStatement ps = null;
int count = 0;
try {
ps = conn.prepareStatement(sql);
JDBCUtil.handleParams(ps, params);
count = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return count;
}
public void insert(Object obj) {
Class clazz = obj.getClass();
TableInfo tableInfo = TableContext.getPoClassTableMap().get(clazz);
List objList = new ArrayList();
StringBuilder sql = new StringBuilder();
// insert into emp(‘ename’,…) values(ename,…)
sql.append(“insert into ” + tableInfo.getTname() + ” (“);
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
Object value = field.get(obj);
if (value != null) {
sql.append(field.getName() + “,”);
objList.add(value);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
String sqlStr = sql.toString();
sqlStr = sqlStr.substring(0, sqlStr.length() – 1);
sql = new StringBuilder(sqlStr);
sql.append(” ) values(“);
for (Object field : objList) {
sql.append(“?,”);
}
sqlStr = sql.toString();
sqlStr = sqlStr.substring(0, sqlStr.length() – 1) + “);”;
System.out.println(“==================/n” + sqlStr);
executeDML(sqlStr, objList.toArray());
}
public void delete(Class clazz, Object id) {
Map<Class, TableInfo> stringTableInfoMap = TableContext.getPoClassTableMap();
TableInfo tableInfo = stringTableInfoMap.get(clazz);
//根据主键进行删除
ColumnInfo priKey = tableInfo.getOnlyPriKey();
String sql = “delete from ” + tableInfo.getTname() + ” where ” + priKey.getName() + ” = ?”;
executeDML(sql, new Object[]{id});
}
public void delete(Object obj) {
Map<Class, TableInfo> classTableInfoMap = TableContext.getPoClassTableMap();
Class clazz = obj.getClass();
TableInfo tableInfo = classTableInfoMap.get(clazz);
Object id = ReflectUtil.invokeGet(tableInfo.getOnlyPriKey().getName(), obj);
delete(clazz, id);
}
public int update(Object obj, String[] fieldNames) {
Class clazz = obj.getClass();
TableInfo tableInfo = TableContext.getPoClassTableMap().get(clazz);
ColumnInfo priKey = tableInfo.getOnlyPriKey();
List paramList = new ArrayList();
StringBuilder sql = new StringBuilder();
sql.append(“update ” + tableInfo.getTname() + ” set “);
for (String field : fieldNames) {
Object value = ReflectUtil.invokeGet(field, obj);
if (value != null) {
sql.append(” ” + field + “=?,”);
paramList.add(value);
}
}
sql.setCharAt(sql.length() – 1, ‘ ‘);
String keyValue = priKey.getName();
Object value = ReflectUtil.invokeGet(keyValue, obj);
if (value != null) {
sql.append(” where ” + priKey.getName() + ” =?”);
paramList.add(value);
}
System.out.println(“======================/n” + sql.toString());
return executeDML(sql.toString(), paramList.toArray());
}
public List queryRows(String sql, Class clazz, Object[] params) {
List list = null;
Connection conn = DBManager.getConn();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
JDBCUtil.handleParams(ps, params);
rs = ps.executeQuery();
while (rs.next()) {
if (list == null) {
list = new ArrayList();
}
Object rowObj = clazz.newInstance();
ResultSetMetaData metaData = rs.getMetaData();
for (int i = 0; i < metaData.getColumnCount(); i++) {
String columnName = metaData.getColumnLabel(i + 1);
Object columnValue = rs.getObject(i + 1);
ReflectUtil.invokeSet(rowObj, columnName, columnValue);
}
list.add(rowObj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
public Object uniqueRow(String sql, Class clazz, Object[] params) {
List list = queryRows(sql, clazz, params);
return list == null || list.size() == 0 ? null : list.get(0);
}
/**
* select count(*) from emp
*
* @param sql
* @param params
* @return
*/
public Object queryValue(String sql, Object[] params) {
Connection conn = DBManager.getConn();
PreparedStatement ps = null;
ResultSet rs = null;
Object value = null;
try {
ps = conn.prepareStatement(sql);
JDBCUtil.handleParams(ps, params);
rs = ps.executeQuery();
while (rs.next()) {
value = rs.getObject(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return value;
}
public Number queryNumber(String sql, Object[] params) {
return (Number) queryValue(sql, params);
}
public void update(Object obj) {
Class clazz = obj.getClass();
TableInfo tableInfo = TableContext.getPoClassTableMap().get(clazz);
ColumnInfo prikey = tableInfo.getOnlyPriKey();
List paramList = new ArrayList();
StringBuilder sql = new StringBuilder();
sql.append(“update ” + tableInfo.getTname() + ” set “);
Map<String, ColumnInfo> columnMap = tableInfo.getColumns();
Set<String> set = columnMap.keySet();
for (String column : set) {
if (prikey.getName().equals(column)) {
continue;
}
try {
Field field = clazz.getDeclaredField(column);
field.setAccessible(true);
Object value = field.get(obj);
if (value != null) {
sql.append(” ” + column + “= ?,”);
paramList.add(value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
String sqlStr = sql.toString();
sqlStr = sqlStr.substring(0, sqlStr.length() – 1);
sql = new StringBuilder(sqlStr);
sql.append(” where ” + prikey.getName() + “=?”);
try {
Field keyField = clazz.getDeclaredField(prikey.getName());
keyField.setAccessible(true);
Object value = keyField.get(obj);
if (value != null) {
paramList.add(value);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(“======================/n” + sql);
executeDML(sql.toString(), paramList.toArray());
}
/**
* 以下使用模板方法 查询
*/
public abstract List queryMethod(String sql, Class clazz, ResultSet rs);
public List executeQueryTemplateMethod(String sql, Class clazz, Object[] params ){
Connection conn = DBManager.getConn();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
JDBCUtil.handleParams(ps, params);
rs = ps.executeQuery();
return queryMethod(sql, clazz, rs);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 使用回调
* @param sql
* @param clazz
* @param params
* @param callBack
* @return
*/
public List executeQueryTemplateMethod(String sql, Class clazz, Object[] params, CallBack callBack ){
Connection conn = DBManager.getConn();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
JDBCUtil.handleParams(ps, params);
rs = ps.executeQuery();
return callBack.doExecute(rs);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
public abstract List queryRows2(String sql, Class clazz, Object[] params );
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
5)query实现类:
1
package main.com.oxx.sorm.core;
import main.com.oxx.sorm.util.ReflectUtil;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
public class MyQuery extends Query {
@Override
public List queryMethod(String sql, Class clazz, ResultSet rs) {
try {
List list = new ArrayList();
while (rs.next()) {
Object rowObj = clazz.newInstance();
ResultSetMetaData metaData = rs.getMetaData();
for (int i = 0; i < metaData.getColumnCount(); i++) {
String columnName = metaData.getColumnLabel(i + 1);
Object columnValue = rs.getObject(i + 1);
ReflectUtil.invokeSet(rowObj, columnName, columnValue);
}
list.add(rowObj);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public List queryRows2(String sql, Class clazz, Object[] params) {
return executeQueryTemplateMethod(sql, clazz, params, new CallBack() {
@Override
public List doExecute(ResultSet rs) {
try {
List list = new ArrayList();
while (rs.next()) {
Object rowObj = clazz.newInstance();
ResultSetMetaData metaData = rs.getMetaData();
for (int i = 0; i < metaData.getColumnCount(); i++) {
String columnName = metaData.getColumnLabel(i + 1);
Object columnValue = rs.getObject(i + 1);
ReflectUtil.invokeSet(rowObj, columnName, columnValue);
}
list.add(rowObj);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
};
});
}
}
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
6)回调接口:
1
package main.com.oxx.sorm.core;
import java.sql.ResultSet;
import java.util.List;
public interface CallBack {
List doExecute( ResultSet resultSet);
}
1
2
3
4
5
6
7
8
9
7)类结构与表映射类:
1
package main.com.oxx.sorm.core;
import main.com.oxx.sorm.bean.ColumnInfo;
import main.com.oxx.sorm.bean.TableInfo;
import main.com.oxx.sorm.util.StringUtil;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static main.com.oxx.sorm.util.JavaFileUtils.createJavaPOFile;
/**
* 负责管理数据库表结构与类的关系
*/
public class TableContext {
//表名与表信息
private static Map<String, TableInfo> tables = new HashMap<String, TableInfo>();
//po的class对象与表信息
private static Map<Class, TableInfo> poClassTableMap = new HashMap<Class, TableInfo>();
static{
Connection conn = DBManager.getConn();
try {
DatabaseMetaData databaseMetaData = conn.getMetaData();
ResultSet tableSet = databaseMetaData.getTables(null, “%”, “%”, new String[]{“TABLE”});
while(tableSet.next()){
String tableName = (String)tableSet.getObject(“TABLE_NAME”);
TableInfo tableInfo = new TableInfo(tableName, new ArrayList<ColumnInfo>(), new HashMap<String, ColumnInfo>());
tables.put(tableName, tableInfo);
ResultSet columnSet = databaseMetaData.getColumns(null, “%”, tableName, “%”);
while(columnSet.next()){
ColumnInfo columnInfo = new ColumnInfo(columnSet.getString(“COLUMN_NAME”),
columnSet.getString(“TYPE_NAME”), 0);
tableInfo.getColumns().put(columnSet.getString(“COLUMN_NAME”), columnInfo);
}
ResultSet keySet = databaseMetaData.getPrimaryKeys(null, “%”, tableName);
while(keySet.next()){
ColumnInfo columnInfo2 = tableInfo.getColumns().get(keySet.getObject(“COLUMN_NAME”));
columnInfo2.setKeyType(1);
tableInfo.getListPriKey().add(columnInfo2);
}
if(tableInfo.getListPriKey().size() > 0){
tableInfo.setOnlyPriKey(tableInfo.getListPriKey().get(0));
}
}
} catch (Exception e) {
e.printStackTrace();
}
//更新po类文件
updateJavaPoFile();
//加载class类
loadPOTable();
}
public static Map<String, TableInfo> getTableInfo(){
return tables;
}
public static void updateJavaPoFile(){
Map<String, TableInfo> tableMap = TableContext.getTableInfo();
for(TableInfo table : tableMap.values()){
createJavaPOFile(table, new MySqlTypeConvertor());
}
}
public static Map<String, TableInfo> getTables() {
return tables;
}
public static void setTables(Map<String, TableInfo> tables) {
TableContext.tables = tables;
}
public static Map<Class, TableInfo> getPoClassTableMap() {
return poClassTableMap;
}
public static void setPoClassTableMap(Map<Class, TableInfo> poClassTableMap) {
TableContext.poClassTableMap = poClassTableMap;
}
public static void loadPOTable(){
for(TableInfo tableInfo : tables.values()){
try {
Class clazz = Class.forName(DBManager.getConfiguration().getPoPackage() + “.” +StringUtil.firstChar2UpperCase(tableInfo.getTname()));
poClassTableMap.put(clazz, tableInfo);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
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
8)类型转换接口:
1
package main.com.oxx.sorm.core;
/**
* 负责java类型与数据库类型 转换
*/
public interface TypeConvertor {
/**
* 将数据库类型 转化为java数据类型
* @param columnType
* @return
*/
public String databaseType2JavaType(String columnType);
/**
* 将java类型转化为数据库类型
* @param javaType
* @return
*/
public String javaType2DatabaseType(String javaType);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
3,util包下的工具类:
1)java类文件生成:
package main.com.oxx.sorm.util;
import main.com.oxx.sorm.bean.ColumnInfo;
import main.com.oxx.sorm.bean.Configuration;
import main.com.oxx.sorm.bean.JavaFieldGetSet;
import main.com.oxx.sorm.bean.TableInfo;
import main.com.oxx.sorm.core.DBManager;
import main.com.oxx.sorm.core.MySqlTypeConvertor;
import main.com.oxx.sorm.core.TableContext;
import main.com.oxx.sorm.core.TypeConvertor;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 生成java文件 常用操作
*/
public class JavaFileUtils {
public static JavaFieldGetSet createFieldGetSetInfoSrc(ColumnInfo columnInfo, TypeConvertor typeConvertor){
JavaFieldGetSet javaFieldGetSet = new JavaFieldGetSet();
//private int id
String javaFieldType = typeConvertor.databaseType2JavaType(columnInfo.getDataType());
javaFieldGetSet.setFieldInfo(“/tprivate” + ” ” + javaFieldType
+ ” ” + columnInfo.getName() + “;/n”);
//public int getId(){return id}
StringBuilder getSb = new StringBuilder();
getSb.append(“/tpublic ” + javaFieldType + ” ” + “get”+StringUtil.firstChar2UpperCase(columnInfo.getName()) + “(){/n”);
getSb.append(“/t/treturn ” + columnInfo.getName() + “;/n”);
getSb.append(“/t}/n”);
javaFieldGetSet.setGetInfo(getSb.toString());
//public void setId(Integer id){this.id = id}
StringBuilder setSb = new StringBuilder();
setSb.append(“/tpublic void ” + “set”+ StringUtil.firstChar2UpperCase(columnInfo.getName()) + “( “);
setSb.append( javaFieldType +” ” + columnInfo.getName() + “){/n”);
setSb.append(“/t/t this.”+columnInfo.getName() + ” =” + columnInfo.getName() + “;/n”);
setSb.append(“/t}/n”);
javaFieldGetSet.setSetInfo(setSb.toString());
return javaFieldGetSet;
}
public static String createJavaSrc(TableInfo tableInfo, TypeConvertor typeConvertor){
List<JavaFieldGetSet> javaFieldGetSets = new ArrayList<JavaFieldGetSet>();
Map<String, ColumnInfo> columns = tableInfo.getColumns();
for(ColumnInfo columnInfo : columns.values()){
javaFieldGetSets.add(createFieldGetSetInfoSrc(columnInfo, typeConvertor));
}
StringBuilder javaSrc = new StringBuilder();
//生成包路径
Configuration config = DBManager.getConfiguration();
String srcPackage = config.getPoPackage();
javaSrc.append(“package ” + srcPackage + “; /n/n”);
//生成 import 语句
javaSrc.append(“import java.sql.*;/n”);
javaSrc.append(“import java.util.*; /n/n/n”);
//生成类名
javaSrc.append(“public class ” + StringUtil.firstChar2UpperCase(tableInfo.getTname()) + “{/n/n”);
//生成属性 private Integer id;
for(JavaFieldGetSet javaFieldGetSet : javaFieldGetSets){
javaSrc.append(javaFieldGetSet.getFieldInfo() + “/n”);
}
javaSrc.append(“/n”);
//生成getset方法
for(JavaFieldGetSet javaFieldGetSet : javaFieldGetSets){
javaSrc.append(javaFieldGetSet.getGetInfo());
javaSrc.append(javaFieldGetSet.getSetInfo());
}
javaSrc.append(“/n}”);
return javaSrc.toString();
}
public static void createJavaPOFile(TableInfo table, TypeConvertor typeConvertor){
String src = createJavaSrc(table, typeConvertor);
System.out.println(src);
String srcPath = DBManager.getConfiguration().getSrcPath();
String poPackage = (DBManager.getConfiguration().getPoPackage()).replaceAll(“//.”, “////”);
String dirPath = srcPath + “/” + poPackage;
File file = new File(dirPath);
if(!file.exists()){
file.mkdirs();
}
String filePath = dirPath + “/” + StringUtil.firstChar2UpperCase(table.getTname()) + “.java”;
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(filePath));
bw.write(src);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
Map<String, TableInfo> tableMap = TableContext.getTableInfo();
for(TableInfo table : tableMap.values()){
createJavaPOFile(table, new MySqlTypeConvertor());
}
}
}
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
2)JDBCUtil工具类:
1
package main.com.oxx.sorm.util;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCUtil {
public static void handleParams(PreparedStatement ps ,Object[] params){
for(int i = 0; i < params.length; i++){
try {
ps.setObject(i + 1, params[i]);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
3)反射工具类:
1
package main.com.oxx.sorm.util;
import java.lang.reflect.Method;
public class ReflectUtil {
public static Object invokeGet(String fieldName, Object obj){
Class clazz = obj.getClass();
try {
Method method = clazz.getDeclaredMethod(“get” + StringUtil.firstChar2UpperCase(fieldName));
return method.invoke(obj, null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void invokeSet(Object obj, String columnName, Object columnValue){
Method method = null;
try {
if(columnValue != null){
method = obj.getClass().getDeclaredMethod(“set”+ StringUtil.firstChar2UpperCase(columnName),
columnValue.getClass());
method.invoke(obj, columnValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
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
4)字符串工具类:
package main.com.oxx.sorm.util;
public class StringUtil {
public static String firstChar2UpperCase(String str){
return str.toUpperCase().substring(0, 1) + str.substring(1);
}
}
1
2
3
4
5
6
7
8
9
4.配置文件db.properties:
driver=com.mysql.jdbc.Driver
url=jdbc/:mysql/://localhost/:3306/test
user=root
pwd=root
srcPath=C://Users//Administrator//IdeaProjects//mysorm//src
poPackage=com.oxx.sorm.po
queryClass=main.com.oxx.sorm.core.MyQuery
1
2
3
4
5
6
7
8
5.应用类App:
import com.oxx.sorm.po.Emp;
import main.com.oxx.sorm.core.Query;
import main.com.oxx.sorm.core.QueryFactory;
import java.util.List;
public class App {
public static void main(String[] args) throws CloneNotSupportedException {
Emp emp = new Emp();
emp.setId(112);
emp.setEname(“欣淡定”);
emp.setEage(113);
String sql = “select * from emp where salary > ?”;
Query query = QueryFactory.createQuery();
List list = query.queryRows2(sql, Emp.class, new Object[]{100});
System.out.println(list);
}
}
————————————————
版权声明:本文为CSDN博主「欣淡定」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xindanding/article/details/111
原创文章,作者:1402239773,如若转载,请注明出处:https://blog.ytso.com/276663.html