JDBC 实现通用的增删改查基础类方法

时间:2022-06-20 08:48:40

java中关于数据的管理有很多的框架,如hibernate、mybatis等,但我最开始学习的就是JDBC,我觉得JDBC还是很不错的,它让我更深层次的了解了数据的操作,今天我将我写过的JDBC基础类再写一遍!加深下记忆!!!

先将通用的增查实现类BaseDAO贴上

?
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package com.shude.DAO;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.shude.DAO.im.IBaseDAO;
import com.shude.util.ConfigUtil;
import com.shude.util.JdbcUtil;
import com.shude.util.PageUtil;
/**
 * 通用的增删改查实现类
 * @author Administrator
 *
 * @param <E>
 */
public class BaseDAO<E> implements IBaseDAO<E> {
    protected static ConfigUtil configUtil;
    protected Class<?> cls;
    /**
     * 获取包名、类名
     */
    public BaseDAO(){
        Class<?> clsTemp = this.getClass();
        Type type = clsTemp.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] types = ((ParameterizedType) type).getActualTypeArguments();
            cls = (Class<?>) types[0];
        }
    }
    /**
     * 获取对应类的数据库中的表名
     */
    static{
        configUtil = ConfigUtil.newInstance("/tabORM.properties");
    }
    
    /**
     * 保存方法
     */
    public boolean saveInfo(E e) {
        boolean flag = true;
        try {
            Class<?> cls = e.getClass();
            //获取表名
            String tableName = configUtil.getVal(cls.getName());
            //获取主键
            String prykey = getPrimKey(tableName);
            //记录数据列
            List<String> filedList = new ArrayList<String>();
            //获取sql语句
            String sql = getsavesql(tableName,prykey,filedList);
            //执行sql
            flag = excuteSQL(sql,e,filedList);
        } catch (Exception e1) {
            flag = false;
            e1.printStackTrace();
        }
        return flag;
    }
    
    /**
     * 修改方法
     */
    public void modifyInfo(E e) {
        Class<?> cls = e.getClass();
        //获取表名
        String tableName = configUtil.getVal(cls.getName());
        //获取主键
        String prykey = getPrimKey(tableName);
        //记录数据列
        List<String> filedList = new ArrayList<String>();
        //获取sql语句
        String sql = getmodifysql(tableName,prykey,filedList);
        //添加主键到集合
        filedList.add(prykey);
        //执行sql
        excuteSQL(sql,e,filedList);
    }
  
    /**
     * 删除方法
     */
    public void deleteInfo(Object id) {
        //获取表名
        String tableName = configUtil.getVal(cls.getName());
        //获取主键
        String prykey = getPrimKey(tableName);
        //获取sql语句
        String sql = "update "+tableName+" set status='1' where "+prykey+"=?";
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            conn = JdbcUtil.getConn();
            pstm = conn.prepareStatement(sql);
            pstm.setObject(1, id);
            pstm.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.closeConn(conn);
        }  
    }
    /**
     * 查询全部方法
     */
    public void queryinfo(PageUtil<E> pageUtil) {
        E e = pageUtil.getEntity();
        //获取表名
        String tableName = configUtil.getVal(cls.getName());
        //获取查询条件
        Map<String,Object> paramMap = getParamMap(e);
        //获取sql
        String sql = getquerySQL(paramMap,tableName);
        sql += " limit ?,?";
        paramMap.put("pageSize", (pageUtil.getPageSize() - 1)*pageUtil.getPageNum());
        paramMap.put("pageNum", pageUtil.getPageNum());
        //执行SQL
        excutQuery(pageUtil,sql,paramMap,tableName);
        
    }
    
    /**
     * 单个查询方法
     */
    public E queryById(Object id) {
        //获取表名
                String tableName = configUtil.getVal(cls.getName());
                //获取主键
                String prykey = getPrimKey(tableName);
                //获取sql
                String sql = "select * from "+tableName+" where 1 = 1 and "+prykey+" = ?";
                //执行SQL
                Connection conn = null;
                PreparedStatement pstm = null;
                ResultSet rs = null;
                E e = null;
                try {
                    conn = JdbcUtil.getConn();
                    pstm = conn.prepareStatement(sql);
                    pstm.setObject(1, id);
                    rs = pstm.executeQuery();
                    List<E> list = getEntityList(rs);
                    e = list.get(0);       
                } catch (Exception ex) {
                    ex.printStackTrace();
                }finally{
                    JdbcUtil.closeConn(conn);
                }
                return e;
    }
    
    /**
     * 获取总条数
     * @param paramMap
     * @param tableName
     * @return
     */
  private Integer getPagenumsss(Map<String, Object> paramMap, String tableName) {
    paramMap.remove("pageSize");
        paramMap.remove("pageNum");
        String sql = getquerySQL(paramMap,tableName);
        sql = "select count(*) from ("+sql+") tempTab";
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        Integer pagenumsss = 0;
        try {
            conn = JdbcUtil.getConn();
            pstm = conn.prepareStatement(sql);
            int i = 1;
            for (Entry<String,Object> entry : paramMap.entrySet()) {
                Object val = entry.getValue();
                if(val instanceof java.lang.String){
                    pstm.setString(i, "%"+val.toString()+"%");
                }else if(val instanceof java.lang.Integer){
                    pstm.setInt(i, Integer.parseInt(val.toString()));
                }
                i++;
            }
            rs = pstm.executeQuery();
            while(rs.next()){
                pagenumsss = rs.getInt(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUtil.closeConn(conn);
        }
        return pagenumsss;
    }
    /**
   * 获取查询SQL
   * @param paramMap
   * @param tableName
   * @return
   */
    private String getquerySQL(Map<String, Object> paramMap, String tableName) {
        StringBuffer sql = new StringBuffer();
        sql.append("select * from ")
        .append(tableName)
        .append(" where 1 = 1 and status='0' ");
        List<String> columlist = getTableColumns(tableName);
        for (Entry<String,Object> entry : paramMap.entrySet()) {
            String columName = entry.getKey();
            for (String colnName : columlist) {
                if(colnName.equalsIgnoreCase(columName)){
                    if(entry.getValue() instanceof java.lang.String){
                        sql.append(" and ").append(columName).append(" like ?");
                    }else{
                        sql.append(" and ").append(columName).append("=?");
                    }
                    break;
                }
            }
        }
        return sql.toString();
    }
  /**
   * 获取查询条件
   * @param e
   * @return
   */
    private Map<String, Object> getParamMap(E e) {
        Map<String,Object> paramMap = new LinkedHashMap<String,Object>();
        Field[] fields = e.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object val = field.get(e);
                if(val != null && !"".equals(val.toString())){
                    paramMap.put(field.getName(), val);
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            
        }
        return paramMap;
    }
    
    /**
   * 获取主键
   * @param tableName
   * @return
   */
    private String getPrimKey(String tableName) {
        Connection conn = null;
        DatabaseMetaData metaData = null;
        ResultSet rs = null;
        String primKeyName = null;
        try {
            conn = JdbcUtil.getConn();
            metaData = conn.getMetaData();
            rs = metaData.getPrimaryKeys(conn.getCatalog(), null, tableName.toUpperCase());
            while (rs.next()) {
                primKeyName = rs.getString("COLUMN_NAME");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JdbcUtil.closeConn(conn);
        }
        return primKeyName;
    }
    /**
     * 保存方法执行SQL
     * @param sql
     * @param e
     * @param filedList
     * @return
     */
    private boolean excuteSQL(String sql, E entity, List<String> filedList) {
        boolean flag = true;
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            conn = JdbcUtil.getConn();
            pstm = conn.prepareStatement(sql);
            //赋值
            int i = 1;
            for (String columName : filedList) {
                Object val = getFieldValue(entity,columName);
                pstm.setObject(i, val);
                i++;
            }
            pstm.execute();
        } catch (SQLException e1) {
            e1.printStackTrace();
            flag = false;
        }finally{
            JdbcUtil.closeConn(conn);
        }
        return flag;
    }
    /**
   * 获取修改方法的SQL
   * @param tableName
   * @param prykey
   * @param filedList
   * @return
   */
    private String getmodifysql(String tableName, String prykey, List<String> filedList) {
        StringBuffer sql = new StringBuffer();
        sql.append("update ").append(tableName).append(" set ");
        List<String> columnList = getTableColumns(tableName);
        for (String columnName : columnList) {
            if (!columnName.equalsIgnoreCase(prykey)) {
                filedList.add(columnName);
                sql.append(columnName).append("=?,");
            }
        }
        if (sql.toString().endsWith(",")) {
            sql = new StringBuffer(sql.substring(0,sql.length()-1));
        }
        sql.append(" where ").append(prykey).append("=?");
        return sql.toString();
    }
  /**
   * 执行查询全部SQL
   * @param pageUtil
   * @param sql
   * @param paramMap
   * @param tableName
   */
    private void excutQuery(PageUtil<E> pageUtil, String sql, Map<String, Object> paramMap, String tableName) {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtil.getConn();
            pstm = conn.prepareStatement(sql);
            int i = 1;
            for (Entry<String,Object> entry : paramMap.entrySet()) {
                Object val = entry.getValue();
                if(val instanceof java.lang.String){
                    pstm.setString(i, "%"+val.toString()+"%");
                }else if(val instanceof java.lang.Integer){
                    pstm.setInt(i, Integer.parseInt(val.toString()));
                }
                i++;
            }
            rs = pstm.executeQuery();
            List<E> list = getEntityList(rs);
            //封装查询结果
            pageUtil.setList(list);
            //封装总条数
            pageUtil.setPageNumSum(getPagenumsss(paramMap,tableName));
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcUtil.closeConn(conn);
        }
    }
    /**
     * 获取表中属性
     * @param entity
     * @param columName
     * @return
     */
  private Object getFieldValue(E entity, String columName) {
      Class<?> cls = entity.getClass();
        Object value = null;
        //获取类中的所有成员属性
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            //获取属性名称
            String fieldName = field.getName();
            //判断属性名称是否与列名相同
            if (fieldName.equalsIgnoreCase(columName)) {
                //根据规则获取方法名称
                String methodName = "get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
                try {
                    //根据方法名称获取方法对象
                    Method method = cls.getMethod(methodName);
                    //执行方法并获取返回值
                    value = method.invoke(entity);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
        }
        return value;
    }
/**
  * 保存方法获取SQL
  * @param tableName
  * @param prykey
  * @param filedList
  * @return
  */
    private String getsavesql(String tableName, String prykey, List<String> filedList) {
        StringBuffer sql = new StringBuffer();
        sql.append("insert into ").append(tableName).append(" (");
            List<String> columnList = getTableColumns(tableName);
            for (String string : columnList) {
                if (!string.equalsIgnoreCase(prykey)) {
                    sql.append(string).append(",");
                    filedList.add(string);
                }
            }
            if (sql.toString().endsWith(",")) {
                sql = new StringBuffer(sql.substring(0,sql.length()-1));
            }
            sql.append(") value (");
            for (int i = 0; i <filedList.size(); i++) {
                
                sql.append("?,");
                    
            }
            if (sql.toString().endsWith(",")) {
                sql = new StringBuffer(sql.substring(0,sql.length()-1));
            }
            sql.append(")");
        return sql.toString();
    }
  
    /**
     * 获取表列
     * @param tableName
     * @return
     */
    private List<String> getTableColumns(String tableName) {
        List<String> columnList = new ArrayList<String>();
        Connection conn = null;
        DatabaseMetaData metaData = null;
        ResultSet rs = null;
        conn = JdbcUtil.getConn();
        try {
            metaData = conn.getMetaData();
            rs = metaData.getColumns(conn.getCatalog(),null,tableName.toUpperCase(),null);
            while (rs.next()) {
                String clumnName = rs.getString("COLUMN_NAME");
                columnList.add(clumnName);
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }
        finally{
            JdbcUtil.closeConn(conn);
        }
        return columnList;
  }
  /**
   * 封装查询结果
   * @param rs
   * @return
   * @throws Exception
   */
    @SuppressWarnings("unchecked")
    private List<E> getEntityList(ResultSet rs) throws Exception {
        List<E> list = new ArrayList<E>();
        Field[] fields = cls.getDeclaredFields();
        while(rs.next()){
            E e = (E)cls.newInstance();
            for (Field field : fields) {
                try {
                    field.setAccessible(true);
                    String columName = field.getName();
                    String fieldType = field.getType().getSimpleName();
                    if("String".equals(fieldType)){
                        field.set(e, rs.getString(columName));
                    }else if("Integer".equals(fieldType)){
                        field.set(e, rs.getInt(columName));
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
            list.add(e);
        }
        return list;
    }
}

mysql相关配置文件config.properties内容

?
1
2
3
4
5
6
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/dbsda10?characterEncoding=UTF-8
username=root
password=rootroot
temfile=C:\\
image=C:\\images

配置文件读取类ConfigUtil

?
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
package com.shude.util;
import java.io.IOException;
import java.util.Properties;
/**
 * 读取配置文件
 * @author Administrator
 *
 */
public class ConfigUtil {
 private static ConfigUtil configUtil;
 private static final String DEFALT_FILE_PATH="/config.properties";
 private static String name;
 private Properties pop;
 private ConfigUtil(){
 init();
 }
 private void init() {
 pop=new Properties();
 try {
  if(name!=null)
  pop.load(ConfigUtil.class.getResourceAsStream(name));
  pop.load(ConfigUtil.class.getResourceAsStream(DEFALT_FILE_PATH));
 } catch (IOException e) {
  e.printStackTrace();
 }
 }
 public static ConfigUtil newInstance(String name){
 ConfigUtil.name=name;
 if(configUtil==null)
  configUtil=new ConfigUtil();
 return configUtil;
 }
 /**
 * 获取配置文件中右边的值
 * @param key
 * @return */
 public String getVal(String key){
 return pop.getProperty(key);
 }
}

在此之前的条件是数据库的字段名称要与实体类中的名称对应并且相同,有相关的数据表名称及实体类名称所相关的配置文件,配置文件如下:

tabORM.properties

?
1
2
3
4
5
6
com.shude.entity.UserInfo=user_info
com.shude.entity.RoleInfo=role_info
com.shude.entity.FabricInfo=fabric_info
com.shude.entity.ProductInfo=product_info
com.shude.entity.MateInfo=mate_info
com.shude.entity.ProgramInfo=program_info

以上这篇JDBC 实现通用的增删改查基础类方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/qq_36792069/article/details/78953136