最近閑暇時(shí)萌發(fā)寫一寫dao的封裝的例子,就將以前寫的整理一下。
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
|
public class BaseDao<T> { Connection conn; PreparedStatement st; ResultSet rs; JdbcUtil jdbcUtil = new JdbcUtil(); int result = 0 ; private Class<T> persistentClass; @SuppressWarnings ( "unchecked" ) public BaseDaoUtil(){ conn = jdbcUtil.getConnection(); ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass(); persistentClass = (Class<T>) type.getActualTypeArguments()[ 0 ]; } /** * 保存 * @param entity * @return */ public int save(T entity) throws Exception{ String sql = "INSERT INTO " + entity.getClass().getSimpleName().toLowerCase() + " (" ; List<Method> list = this .matchPojoMethods(entity, "get" ); Iterator<Method> iter = list.iterator(); Object obj[] = new Object[list.size()]; int i = 0 ; //拼接字段順序 insert into table name(id,name,email, while (iter.hasNext()) { Method method = iter.next(); sql += method.getName().substring( 3 ).toLowerCase() + "," ; if (method.getReturnType().getSimpleName().indexOf( "Date" ) !=- 1 ) { SimpleDateFormat sbf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); obj[i] = sbf.format(method.invoke(entity, new Object[]{})); } else { obj[i] = method.invoke(entity, new Object[]{}); } i++; } //去掉最后一個(gè),符號(hào)insert insert into table name(id,name,email) values( sql = sql.substring( 0 , sql.lastIndexOf( "," )) + ") values(" ; //拼裝預(yù)編譯SQL語(yǔ)句insert insert into table name(id,name,email) values(?,?,?, for ( int j = 0 ; j < list.size(); j++) { sql += "?," ; } //去掉SQL語(yǔ)句最后一個(gè),符號(hào)insert insert into table name(id,name,email) values(?,?,?); sql = sql.substring( 0 , sql.lastIndexOf( "," )) + ")" ; //到此SQL語(yǔ)句拼接完成,打印SQL語(yǔ)句 System.out.println(sql); try { st = conn.prepareStatement(sql); for ( int j = 0 ; j < obj.length; j++) { st.setObject(j+ 1 , obj[j]); } result = st.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } jdbcUtil.getClose(rs, st, conn); return result; } /** * 刪除 * @param object * @return * @throws SQLException */ public int deleteId(Object object) throws Exception{ String sql = "delete from " + persistentClass.getSimpleName().toLowerCase() + " where " ; //通過子類的構(gòu)造函數(shù),獲得參數(shù)化類型的具體類型.比如BaseDAO<T>也就是獲得T的具體類型 T entity = persistentClass.newInstance(); //存放Pojo(或被操作表)主鍵的方法對(duì)象 Method idMethod = null ; List<Method> list = this .matchPojoMethods(entity, "set" ); Iterator<Method> iter = list.iterator(); //過濾取得Method對(duì)象 while (iter.hasNext()) { Method tempMethod = iter.next(); if (tempMethod.getName().indexOf( "Id" ) != - 1 && tempMethod.getName().substring( 3 ).length() == 2 ) { idMethod = tempMethod; } else if ((entity.getClass().getSimpleName() + "Id" ).equalsIgnoreCase(tempMethod.getName().substring( 3 ))){ idMethod = tempMethod; } } //第一個(gè)字母轉(zhuǎn)為小寫 sql += idMethod.getName().substring( 3 , 4 ).toLowerCase()+idMethod.getName().substring( 4 ) + " = ?" ; System.out.println(sql); st = conn.prepareStatement(sql); //判斷id的類型 if (object instanceof Integer) { st.setInt( 1 , (Integer)object); } else if (object instanceof String){ st.setString( 1 , (String)object); } result = st.executeUpdate(); jdbcUtil.getClose(rs, st, conn); return result; } /** * 修改 * @param entity * @return * @throws Exception */ public int update(T entity) throws Exception{ String sql = "update " + entity.getClass().getSimpleName().toLowerCase() + " set " ; List<Method> list = this .matchPojoMethods(entity, "get" ); //裝載參數(shù) Object obj[] = new Object[list.size()]; int i = 0 ; //臨時(shí)Method對(duì)象,負(fù)責(zé)迭代時(shí)裝method對(duì)象. Method tempMethod = null ; //由于修改時(shí)不需要修改ID,所以按順序加參數(shù)則應(yīng)該把Id移到最后. Method idMethod = null ; Iterator<Method> iter = list.iterator(); while (iter.hasNext()) { tempMethod = iter.next(); //如果方法名中帶有ID字符串并且長(zhǎng)度為2,則視為ID. if (tempMethod.getName().lastIndexOf( "Id" ) != - 1 && tempMethod.getName().substring( 3 ).length() == 2 ) { obj[list.size()- 1 ] = tempMethod.invoke(entity, new Object[]{}); //把ID字段的對(duì)象存放到一個(gè)變量中,然后在集合中刪掉. idMethod = tempMethod; iter.remove(); //如果方法名去掉set/get字符串以后與pojo + "id"想符合(大小寫不敏感),則視為ID } else if ((entity.getClass().getSimpleName() + "Id" ).equalsIgnoreCase(tempMethod.getName().substring( 3 ))) { obj[list.size()- 1 ] = tempMethod.invoke(entity, new Object[]{}); idMethod = tempMethod; iter.remove(); } } //把迭代指針移到第一位 iter = list.iterator(); while (iter.hasNext()) { tempMethod = iter.next(); sql += tempMethod.getName().substring( 3 ).toLowerCase() + "= ?," ; obj[i] = tempMethod.invoke(entity, new Object[]{}); i++; } //去掉最后一個(gè),符號(hào) sql = sql.substring( 0 ,sql.lastIndexOf( "," )); //添加條件 sql += " where " + idMethod.getName().substring( 3 ).toLowerCase() + " = ?" ; //SQL拼接完成,打印SQL語(yǔ)句 System.out.println(sql); st = conn.prepareStatement(sql); for ( int j = 0 ; j < obj.length; j++) { st.setObject(j+ 1 , obj[j]); } result = st.executeUpdate(); jdbcUtil.getClose(rs, st, conn); return result; } public T findById(Object object) throws Exception{ String sql = "select * from " + persistentClass.getSimpleName().toLowerCase() + " where " ; //通過子類的構(gòu)造函數(shù),獲得參數(shù)化類型的具體類型.比如BaseDAO<T>也就是獲得T的具體類型 T entity = persistentClass.newInstance(); //存放Pojo(或被操作表)主鍵的方法對(duì)象 Method idMethod = null ; List<Method> list = this .matchPojoMethods(entity, "set" ); Iterator<Method> iter = list.iterator(); //過濾取得Method對(duì)象 while (iter.hasNext()) { Method tempMethod = iter.next(); if (tempMethod.getName().indexOf( "Id" ) != - 1 && tempMethod.getName().substring( 3 ).length() == 2 ) { idMethod = tempMethod; } else if ((entity.getClass().getSimpleName() + "Id" ).equalsIgnoreCase(tempMethod.getName().substring( 3 ))){ idMethod = tempMethod; } } //第一個(gè)字母轉(zhuǎn)為小寫 sql += idMethod.getName().substring( 3 , 4 ).toLowerCase()+idMethod.getName().substring( 4 ) + " = ?" ; System.out.println(sql); st = conn.prepareStatement(sql); //判斷id的類型 if (object instanceof Integer) { st.setInt( 1 , (Integer)object); } else if (object instanceof String){ st.setString( 1 , (String)object); } rs = st.executeQuery(); //把指針指向迭代器第一行 iter = list.iterator(); //封裝 while (rs.next()) { while (iter.hasNext()) { Method method = iter.next(); if (method.getParameterTypes()[ 0 ].getSimpleName().indexOf( "String" ) != - 1 ) { //由于list集合中,method對(duì)象取出的方法順序與數(shù)據(jù)庫(kù)字段順序不一致(比如:list的第一個(gè)方法是setDate,而數(shù)據(jù)庫(kù)按順序取的是"123"值) //所以數(shù)據(jù)庫(kù)字段采用名字對(duì)應(yīng)的方式取. this .setString(method, entity, rs.getString(method.getName().substring( 3 ).toLowerCase())); } else if (method.getParameterTypes()[ 0 ].getSimpleName().indexOf( "Date" ) != - 1 ){ this .setDate(method, entity, rs.getDate(method.getName().substring( 3 ).toLowerCase())); } else { this .setInt(method, entity, rs.getInt(method.getName().substring( 3 ).toLowerCase())); } } } jdbcUtil.getClose(rs, st, conn); return entity; } /** * 過濾當(dāng)前Pojo類所有帶傳入字符串的Method對(duì)象,返回List集合. */ private List<Method> matchPojoMethods(T entity,String methodName) { //獲得當(dāng)前Pojo所有方法對(duì)象 Method[] methods = entity.getClass().getDeclaredMethods(); //List容器存放所有帶get字符串的Method對(duì)象 List<Method> list = new ArrayList<Method>(); //過濾當(dāng)前Pojo類所有帶get字符串的Method對(duì)象,存入List容器 for ( int index = 0 ; index < methods.length; index++) { if (methods[index].getName().indexOf(methodName) != - 1 ) { list.add(methods[index]); } } return list; } /** * 參數(shù)類型為String時(shí),為entity字段設(shè)置參數(shù),對(duì)應(yīng)set */ public String setString(Method method, T entity, String arg) throws Exception{ return (String)method.invoke(entity, new Object[]{arg}); } /** * 參數(shù)類型為Date時(shí),為entity字段設(shè)置參數(shù),對(duì)應(yīng)set */ public Date setDate(Method method, T entity, Date arg) throws Exception{ return (Date)method.invoke(entity, new Object[]{arg}); } /** * 參數(shù)類型為Integer或int時(shí),為entity字段設(shè)置參數(shù),對(duì)應(yīng)set */ public Integer setInt(Method method, T entity, Integer arg) throws Exception{ return (Integer)method.invoke(entity, new Object[]{arg}); } } |
以上這篇基于JDBC封裝的BaseDao(實(shí)例代碼)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。