zoukankan      html  css  js  c++  java
  • 反射实现数据库增删改查DAO及DAOImpl源代码(一)

    这是DAO层,第一次尝试,如有bug希望能即使反馈,我们共同进步。具体的用法和实现原理我会在前面几篇博客中补充更新。配置文件及项目目录结构会在下一篇中贴出!

    package com.javasm.supermarket.dao;
    
    import java.util.List;
    import java.util.Map;
    
    public interface DAO {
    	// 增加
    	void addObject(Object o);
    	// 删除
    //	void deleteObject(Object o);
    	// 修改
    	void updateObject(Object o);
    	/**
    	 * 查询,可实现多查询或单一查询
    	 * @param params
    	 * @param tableName
    	 * @return
    	 */
    	List<?> queryObject();
    	
    	void deleteObject();
    }
    

    DAOImpl层源码

    package com.javasm.supermarket.impl;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.lang.reflect.Field;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Timestamp;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Properties;
    
    import com.javasm.supermarket.dao.DAO;
    import com.javasm.supermarket.db.DBConnection;
    
    public class DAOImpl implements DAO {
    	private static Properties objectConfigPath = new Properties();
    	private static Properties objectConfig = new Properties();
    	private static String className;
    	private static Class<?> objectClass;
    	private static Field[] fields;
    	private static String tableName;
    	private static String queryBuilder;
    	private static String deleteBuilder;
    	/**
    	 * 
    	 * 加载配置文件,从配置文件中获取bean和bean对应的表明
    	 * 
    	 */
    	static {
    		try {
    			DAOImpl.class.getClassLoader();
    			InputStream objectConfigPathInputStream = ClassLoader
    					.getSystemResourceAsStream("objectConfigPath.properties");
    			objectConfigPath.load(objectConfigPathInputStream);
    			InputStream objectConfigInputStream = ClassLoader
    					.getSystemResourceAsStream(objectConfigPath
    							.getProperty("objectConfigPath"));
    			objectConfig.load(objectConfigInputStream);
    			className = objectConfig.getProperty("className");
    			tableName = objectConfig.getProperty("tableName");
    			queryBuilder = objectConfig.getProperty("queryBuilder");
    			deleteBuilder = objectConfig.getProperty("deleteBuilder");
    
    			objectClass = Class.forName(className);
    			fields = objectClass.getDeclaredFields();
    
    		} catch (IOException | ClassNotFoundException e) {
    			e.printStackTrace();
    			System.err.println("配置文件加载失败!");
    		}
    	}
    
    	/**
    	 * 插入数据
    	 */
    	@Override
    	public void addObject(Object object) {
    		StringBuilder sql = new StringBuilder("INSERT " + tableName
    				+ " VALUES(");
    		Connection connection = null;
    		PreparedStatement preparedStatement = null;
    		// 用于存放传入的对象的参数,默认将id值(主键)的key设为0,方便条件设置
    		Map<Integer, Object> fieldsValues = new HashMap<Integer, Object>();
    		try {
    			for (int i = 0; i < fields.length; i++) {
    				fields[i].setAccessible(true);
    				fieldsValues.put(i, fields[i].get(object));
    				sql.append("?");
    				if (i < (fields.length - 1))
    					sql.append(", ");
    
    			}
    			sql.append(")");
    			connection = DBConnection.getConnection();
    
    			preparedStatement = connection.prepareStatement(sql.toString());
    			Class<?> fieldClass = null;
    			for (int i = 1; i <= fieldsValues.size(); i++) {
    				/**
    				 * 获取存入map中对象的参数的类类型,根据类类型选择preparedStatement的set方法
    				 */
    				if (fieldsValues.get(i - 1) != null) {
    					fieldClass = fieldsValues.get(i - 1).getClass();
    					// 如果类类型为String.class,则执行setString
    					if (fieldClass.equals(String.class)) {
    						preparedStatement.setString(i,
    								(String) fieldsValues.get(i - 1));
    					}
    					// 如果类类型为Float.class,则执行setString
    					if (fieldClass.equals(Float.class)) {
    						preparedStatement.setFloat(i,
    								(Float) fieldsValues.get(i - 1));
    					}
    					// 如果类类型为Integer.class,则执行setString
    					if (fieldClass.equals(Integer.class)) {
    						preparedStatement.setInt(i,
    								(Integer) fieldsValues.get(i - 1));
    					}
    					// 如果类类型为Timestamp.class,则执行setString
    					if (fieldClass.equals(Timestamp.class)) {
    						preparedStatement.setTimestamp(i, new Timestamp(
    								((Date) fieldsValues.get(i - 1)).getTime()));
    					}
    
    				} else {
    					preparedStatement.setObject(i, null);
    				}
    
    			}
    			// 执行sql语句,返回更新参数
    			int columnsCount = preparedStatement.executeUpdate();
    			System.out.println("有" + columnsCount + "条数据被更新!");
    
    		} catch (SQLException e) {
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			e.printStackTrace();
    		} catch (NumberFormatException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} finally {
    			DBConnection.close(connection, preparedStatement, null);
    		}
    
    	}
    
    	/**
    	 * 
    	 * 删除数据,条件列表为空时删除所有数据
    	 */
    	@Override
    	public void deleteObject() {
    		StringBuilder sql = new StringBuilder(
    				"DELETE FROM order_info WHERE 1=1 ");
    		List<Map<String, Object>> params = builder(deleteBuilder);
    		Connection connection = null;
    		PreparedStatement preparedStatement = null;
    		try {
    			connection = DBConnection.getConnection();
    			if (params != null && params.size() > 0) {
    				for (int i = 0; i < params.size(); i++) {
    					Map<String, Object> map = params.get(i);
    					sql.append(" AND  " + map.get("name") + " "
    							+ map.get("rela") + " " + map.get("value") + " ");
    				}
    			}
    			connection = DBConnection.getConnection();
    			preparedStatement = connection.prepareStatement(sql.toString());
    			preparedStatement.executeLargeUpdate();
    
    		} catch (SQLException e) {
    			e.printStackTrace();
    			System.out.println("删除失败!");
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} finally {
    			DBConnection.close(connection, preparedStatement, null);
    		}
    
    	}
    
    	/**
    	 * 
    	 * 修改数据
    	 * 
    	 */
    	@Override
    	public void updateObject(Object object) {
    		StringBuilder sql = new StringBuilder("UPDATE " + tableName + " SET ");
    		Connection connection = null;
    		PreparedStatement preparedStatement = null;
    		// 用于存放传入的对象的参数,默认将id值(主键)的key设为0,方便条件设置
    		Map<Integer, Object> fieldsValues = new HashMap<Integer, Object>();
    		try {
    			for (int i = 0; i < fields.length; i++) {
    				fields[i].setAccessible(true);
    
    				if (i == 0) {
    					fieldsValues.put(fields.length - 1, fields[i].get(object));
    					continue;
    				}
    				sql.append(fields[i].getName());
    				sql.append("=?");
    				fieldsValues.put(i - 1, fields[i].get(object));
    				if (i < (fields.length - 1))
    					sql.append(", ");
    				if (i == (fields.length - 1)) {
    					sql.append(" WHERE ");
    					sql.append(fields[0].getName());
    					sql.append("=?");
    				}
    
    			}
    			connection = DBConnection.getConnection();
    
    			preparedStatement = connection.prepareStatement(sql.toString());
    			Class<?> fieldClass = null;
    			for (int i = 1; i <= fieldsValues.size(); i++) {
    				/**
    				 * 获取存入map中对象的参数的类类型,根据类类型选择preparedStatement的set方法
    				 */
    				fieldClass = fieldsValues.get(i - 1).getClass();
    				// 如果类类型为String.class,则执行setString
    				if (fieldClass.equals(String.class)) {
    					preparedStatement.setString(i,
    							(String) fieldsValues.get(i - 1));
    				}
    				// 如果类类型为Float.class,则执行setString
    				if (fieldClass.equals(Float.class)) {
    					preparedStatement.setFloat(i,
    							(Float) fieldsValues.get(i - 1));
    				}
    				// 如果类类型为Integer.class,则执行setString
    				if (fieldClass.equals(Integer.class)) {
    					preparedStatement.setInt(i,
    							(Integer) fieldsValues.get(i - 1));
    				}
    				// 如果类类型为Timestamp.class,则执行setString
    				if (fieldClass.equals(Timestamp.class)) {
    					preparedStatement.setTimestamp(i, new Timestamp(
    							((Date) fieldsValues.get(i - 1)).getTime()));
    				}
    
    			}
    			// 执行sql语句,返回更新参数
    			int columnsCount = preparedStatement.executeUpdate();
    			System.out.println("有" + columnsCount + "条数据被更新!");
    
    		} catch (SQLException e) {
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			e.printStackTrace();
    		} catch (NumberFormatException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} finally {
    			DBConnection.close(connection, preparedStatement, null);
    		}
    
    	}
    
    	/**
    	 * 
    	 * 数据查询,查询条件列表为空时查询所有数据
    	 * 
    	 */
    	@Override
    	public List<?> queryObject() {
    		List<Map<String, Object>> params = builder(queryBuilder);
    		List<Object> objectList = new ArrayList<Object>();
    		StringBuilder sql = new StringBuilder("SELECT * FROM " + tableName
    				+ " WHERE 1=1");
    		Connection connection = null;
    		PreparedStatement preparedStatement = null;
    		ResultSet resultSet = null;
    
    		try {
    			connection = DBConnection.getConnection();
    			if (params != null && params.size() > 0) {
    				for (int i = 0; i < params.size(); i++) {
    					Map<String, Object> map = params.get(i);
    					sql.append(" AND  " + map.get("name") + " "
    							+ map.get("rela") + " " + map.get("value") + " ");
    				}
    			}
    			preparedStatement = connection.prepareStatement(sql.toString());
    
    			resultSet = preparedStatement.executeQuery();
    			ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
    			// 获取数据列数
    			int columnsCount = resultSetMetaData.getColumnCount();
    			Field field = null;
    			Object object = null;
    			while (resultSet.next()) {
    				/**
    				 * 获取实例化对象
    				 */
    				object = objectClass.newInstance();
    
    				String columnName = null;
    				String columnTypeName = null;
    				String columnValue = null;
    
    				for (int i = 1; i <= columnsCount; i++) {
    					columnName = resultSetMetaData.getColumnName(i);
    					columnTypeName = resultSetMetaData.getColumnTypeName(i);
    					columnValue = resultSet.getString(i);
    					field = object.getClass().getDeclaredField(columnName);
    					field.setAccessible(true);
    					switch (columnTypeName) {
    					case "INT":
    						field.set(object, Integer.parseInt(columnValue));
    						break;
    					case "TINYINT":
    						field.set(object, Integer.parseInt(columnValue));
    						break;
    					case "VARCHAR":
    						field.set(object, columnValue);
    						break;
    					case "FLOAT":
    						field.set(object, Float.parseFloat(columnValue));
    						break;
    					case "DATETIME":
    						SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
    								"yyyy-MM-dd HH:mm:ss");
    						field.set(object, simpleDateFormat.parse(columnValue));
    						break;
    					}
    
    				}
    				objectList.add(object);
    
    			}
    
    		} catch (SQLException e) {
    			e.printStackTrace();
    		} catch (NoSuchFieldException e) {
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			e.printStackTrace();
    		} catch (NumberFormatException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} catch (ParseException e) {
    			e.printStackTrace();
    		} catch (InstantiationException e) {
    			e.printStackTrace();
    		} finally {
    			DBConnection.close(connection, preparedStatement, resultSet);
    		}
    		return objectList;
    	}
    
    	/**
    	 * 从配置文件中提取删除或查询条件,如果传入的builder为null,则返回空列表
    	 * 
    	 * @param builder
    	 * @return
    	 */
    	private List<Map<String, Object>> builder(String builder) {
    		List<Map<String, Object>> paramList = new ArrayList<Map<String, Object>>();
    		if (builder.equals("null")) {
    			paramList = null;
    		} else {
    			Map<String, Object> param = null;
    			String[] values = null;
    			System.out.println(builder.contains(";"));
    			if (builder.contains(";")) {
    				String[] mapValue = builder.split(";");
    				for (String string : mapValue) {
    					values = string.split(",");
    					param = new HashMap<String, Object>();
    					param.put("name", values[0]);
    					param.put("rela", values[1]);
    					param.put("value", values[2]);
    					paramList.add(param);
    				}
    			} else {
    				values = builder.split(",");
    				param = new HashMap<String, Object>();
    				param.put("name", values[0]);
    				param.put("rela", values[1]);
    				param.put("value", values[2]);
    				paramList.add(param);
    			}
    		}
    		return paramList;
    	}
    
    }
    
    
    
  • 相关阅读:
    Object_Pascal_西门子SCL应用_系列1_初识SCL
    Windows程序设计零基础自学_5_GDI基础_之获取设备内容信息
    Windows程序设计零基础自学_1_Windows程序消息循环机制
    Delphi真的没落了吗?_说Delphi母语Pascal的另一个应用
    C语言学习趣事_关于C语言中的预处理
    C语言学习趣事_关于C语言中的输入输出流
    C语言学习趣事_关于C语言中的空格
    Windows程序设计零基础自学_4_Windows程序的显示和更新_之滚动条处理
    Windows程序设计零基础自学_5_GDI基础
    C语言学习趣事_经典面试题系列_1
  • 原文地址:https://www.cnblogs.com/caoleiCoding/p/9064623.html
Copyright © 2011-2022 走看看