改进dbcp 实现bean的自动映射(修改版 无须传进返回的实体类型 只需传入sql语句即可)...

本文介绍了一种新的SQL查询框架,能够根据SQL语句自动生成对应的实体类,简化了数据库查询过程。通过反射机制实现了查询结果到Java实体的自动转换。

针对昨天写的框架,今天做了修改,实现无须传入返回实体的类型 直接由sql语句进行程序自己创建 更加人性化设计,代码如下

  1. jar包和上一个的jar包完全相同,只贴出代码 

  2. 源代码http://pan.baidu.com/s/1kTFRxll

  3. dbconfig.properties配置文件:需要在配置文件中指明bean实体的包目录

  4. driver = com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost/sharedschool
    username =root
    password=****
    InitialSize=5
    MaxActive=10
    MaxWait=5000
    MinIdle=10
    characterEncoding=characterEncoding=utf-8
    beanUrl=dzu.sc.bean


  5. Data.java

  6. package com.dzu.myDbcp;
    
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    import java.sql.SQLException;
    
    import java.util.Properties;
    
    import org.apache.commons.dbcp.BasicDataSource;
    
    /**
     * 
     * @author zhangjie 数据连接底层帮助类
     */
    public class Data {
    	/**
    	 * 创建数据源
    	 */
    	private static BasicDataSource ds = new BasicDataSource();
    	static {
    		Properties properties = new Properties();
    		try {
    			properties.load(DBHelp.class.getClassLoader().getResourceAsStream(
    					"dbconfig.properties"));
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    
    		String driver = properties.getProperty("driver");
    		String url = properties.getProperty("url");
    		String username = properties.getProperty("username");
    		String password = properties.getProperty("password");
    		String characterEncoding = properties.getProperty("characterEncoding");
    		int InitialSize = Integer.parseInt(properties
    				.getProperty("InitialSize"));
    		int MaxActive = Integer.parseInt(properties.getProperty("MaxActive"));
    		long MaxWait = Long.parseLong(properties.getProperty("MaxWait"));
    		int MinIdle = Integer.parseInt(properties.getProperty("MinIdle"));
    
    		ds.setDriverClassName(driver);
    		ds.setUrl(url);
    		ds.setUsername(username);
    		ds.setPassword(password);
    		ds.setInitialSize(InitialSize);
    		ds.setMaxWait(MaxWait);
    		ds.setMaxActive(MaxActive);
    		ds.setMinIdle(MinIdle);
    		ds.setConnectionProperties(characterEncoding);
    
    	}
    
    	/**
    	 * 
    	 * 获取连接
    	 * 
    	 * @return
    	 */
    	public static Connection getConnection() {
    		try {
    			Connection conn = ds.getConnection();
    			return conn;
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	/**
    	 * 
    	 * 关闭连接
    	 * 
    	 * @param stat
    	 * @param conn
    	 */
    	public static void close(PreparedStatement stat, Connection conn) {
    		close(null, stat, conn);
    	}
    
    	/**
    	 * 
    	 * 关闭连接
    	 * 
    	 * @param rs
    	 * @param stat
    	 * @param conn
    	 */
    	public static void close(ResultSet rs, PreparedStatement stat,
    			Connection conn) {
    		try {
    			if (rs != null) {
    				rs.close();
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				if (stat != null) {
    					stat.close();
    				}
    
    			} catch (SQLException e) {
    				e.printStackTrace();
    			} finally {
    				try {
    					if (conn != null) {
    						conn.close();
    					}
    				} catch (SQLException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    
    }


DBhelp.java

package com.dzu.myDbcp;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.dzu.myDbcp.Data;

;

/**
 * action或者servlet直接访问的数据调用帮助类
 * 
 * @author zhangjie
 * 
 */
public class DBHelp {

	/**
	 * 
	 * 执行增删改
	 * 
	 * @param sql
	 */
	public static int executeSQL(String sql, Object... args) {
		int result = 0;
		Connection conn = null;
		PreparedStatement stat = null;
		try {
			conn = Data.getConnection();
			stat = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				stat.setObject(i + 1, args[i]);
			}

			result = stat.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			Data.close(stat, conn);
		}
		return result;
	}

	/**
	 * 执行查询
	 * 
	 * @param <T>
	 *            返回list<bean> 参数说明 classType 为返回实体的类型
	 * @throws SQLException
	 */
	public static List queryForListBean( String sql,
			Object... args) {
		Class classType=null;
		//很据sql语句动态实例实体类型
		try {
			classType=Class.forName(getBeanUrl(sql));
		} catch (ClassNotFoundException e1) {
			
			e1.printStackTrace();
		}
		List list = null;
		ResultSet rs = null;
		Connection conn = null;
		PreparedStatement stat = null;
		try {
			conn = Data.getConnection();
			stat = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				stat.setObject(i + 1, args[i]);
			}

			rs = stat.executeQuery();
			list = resultSetToList(rs);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			Data.close(stat, conn);
		}
		// 将list注入到bean
		return myReflect.convertList2Bean(classType, list);

	}

	/**
	 * 查询 返回单实体
	 * 
	 * @param <T>
	 * 
	 * @param <T>
	 * @param <T>
	 * @param pojo
	 * @param sql
	 * @param args
	 * @return
	 */
	public static Object queryForbean( String sql,
			Object... args) {
		
		Class classType=null;
		//很据sql语句动态实例实体类型
		try {
			classType=Class.forName("dzu.sc.bean.Acount");
		} catch (ClassNotFoundException e1) {
			
			e1.printStackTrace();
		}
		
		Map map = null;
		ResultSet rs = null;
		Connection conn = null;
		PreparedStatement stat = null;
		try {
			conn = Data.getConnection();
			stat = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				stat.setObject(i + 1, args[i]);
			}

			rs = stat.executeQuery();
			map = (Map) resultSetToList(rs).get(0);
			// 查询结束后映射到bean

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			Data.close(stat, conn);
		}
		return myReflect.convertMap2Bean(classType, map);
	}

	/**
	 * 直接执行查询 返回list集合 注意 :为了便于操作 该list中封装map实现
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	public static List queryForList(String sql, Object... args) {
		List list = null;
		ResultSet rs = null;
		Connection conn = null;
		PreparedStatement stat = null;
		try {
			conn = Data.getConnection();
			stat = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				stat.setObject(i + 1, args[i]);
			}

			rs = stat.executeQuery();
			list = resultSetToList(rs);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			Data.close(stat, conn);
		}

		return list;
	}

	/**
	 * 直接执行查询 返回Map集合,方便多表直接查询 注意 :为了便于操作 该list中封装map实现
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	public static Map queryForMap(String sql, Object... args) {
		Map map = new HashMap();
		ResultSet rs = null;
		Connection conn = null;
		PreparedStatement stat = null;
		try {
			conn = Data.getConnection();
			stat = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				stat.setObject(i + 1, args[i]);
			}

			rs = stat.executeQuery();
			map = (Map) resultSetToList(rs).get(0);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			Data.close(stat, conn);
		}

		return map;
	}

	/**
	 * 将结果result换为list
	 * */
	private static List resultSetToList(ResultSet rs)
			throws java.sql.SQLException {
		if (rs == null)
			return Collections.EMPTY_LIST;
		ResultSetMetaData md = rs.getMetaData();
		int columnCount = md.getColumnCount();
		List list = new ArrayList();

		Map rowData = new HashMap();
		while (rs.next()) {
			rowData = new HashMap(columnCount);

			for (int i = 1; i <= columnCount; i++) {
				rowData.put(md.getColumnName(i), rs.getObject(i));
			}
			list.add(rowData);
		}
		return list;
	}

	/**
	 * 读取配置文件 获取bean的包目录
	 */
	private static String getBeanUrl(String sql) {
		String[] beanNames=sql.split(" ");
		String beanName="";
		String beanUrl="";
		for(int i=0;i<beanNames.length;i++){
			if(beanNames[i].toString().toLowerCase().endsWith("from")){
				beanName=beanNames[i+1];
				break;
			}
		}
		Properties properties = new Properties();
		try {
			properties.load(DBHelp.class.getClassLoader().getResourceAsStream(
					"dbconfig.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		beanUrl=properties.getProperty("beanUrl")+"."+beanName;
		return beanUrl;
	}

}

myReflect.java

package com.dzu.myDbcp;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 采用映射将集合映射到bean的帮助类
 * @author zhangjie
 *
 */
public class myReflect {

	/**
	 * map映射到bean
	 * 返回实体实例
	 * @param <T>
	 * @param pojo
	 * @param map
	 * @return
	 */
	public static <T> Object convertMap2Bean(Class classType,
			Map map) {	
		Object classEntry = null;
		try {
			classEntry = classType.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Iterator it = map.keySet().iterator();
		// 遍历结果集数据列
		while (it.hasNext()) {
			// 获取属性名
			String fieldName = it.next().toString();
			// 属性名首字母大写
			String stringLetter = fieldName.substring(0, 1).toUpperCase();

			// 生成get/set方法名
			String setName = "set" + stringLetter + fieldName.substring(1);
			String getName = "get" + stringLetter + fieldName.substring(1);

			// 方法名反射获取get/set方法
			Method getMethod = null;
			try {
				getMethod = classType.getMethod(getName, new Class[] {});
			} catch (SecurityException e2) {

				e2.printStackTrace();
			} catch (NoSuchMethodException e2) {

				e2.printStackTrace();
			}

			Method setMethod = null;
			try {
				setMethod = classType.getMethod(setName,
						new Class[] { getMethod.getReturnType() });
			} catch (SecurityException e1) {

				e1.printStackTrace();
			} catch (NoSuchMethodException e1) {

				e1.printStackTrace();
			}

			// 通过方法获取参数类型
			Class<? extends Object> fieldType = setMethod.getParameterTypes()[0];
			// 获取数据并做数据类型转换

			String valueString = null;
			try {
				valueString = map.get(fieldName).toString();
			} catch (Exception e) {

			}
			Object value = formatValue(valueString, fieldType);
			// 赋值操作
			try {
				setMethod.invoke(classEntry, new Object[] { value });
			} catch (IllegalArgumentException e) {

				e.printStackTrace();
			} catch (IllegalAccessException e) {

				e.printStackTrace();
			} catch (InvocationTargetException e) {

				e.printStackTrace();
			}

		}

		return classEntry;
	}

	/**
	 * list映射到bean
	 * 
	 * @param <T>
	 * @param pojo
	 * @param map
	 * @return
	 */
	public static  List convertList2Bean(Class classType, List list) {

		List lPojos = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			Map map = new HashMap();
			map = (Map) list.get(i);
			Object t = convertMap2Bean(classType, map);
			lPojos.add(t);
		}
		return lPojos;
	}

	/**
	 * 进行数据转换
	 * 供以上两个方法使用
	 * @param fieldValue
	 * @param fieldType
	 * @return
	 */
	private static Object formatValue(String fieldValue,
			Class<? extends Object> fieldType) {
		Object value = null;

		if (fieldType == Integer.class || "int".equals(fieldType.getName())) {
			if (fieldValue != null) {
				value = Integer.parseInt(fieldValue);
			}
			else{
				value=0;
			}
		} else if (fieldType == Float.class
				|| "float".equals(fieldType.getName())) {
			if (fieldValue != null) {
				value = Float.parseFloat(fieldValue);
			}
			else{
				value=0;
			}
		} else if (fieldType == Double.class
				|| "double".equals(fieldType.getName())) {
			if (fieldValue != null) {
				value = Double.parseDouble(fieldValue);
			}
			else{
				value=0;
			}
		} else if (fieldType == Date.class || fieldType == java.util.Date.class) {
			if (fieldValue != null) {
				value = Timestamp.valueOf(fieldValue);
			}
			else{
				value=0;
			}
		} else {
			value = fieldValue;
		}

		return value;
	}
	
	
}

test.java

package com.dzu.myDbcp;

import dzu.sc.bean.Acount;

public class test {
public static void main(String[] args) {
	Acount acount=(Acount) DBHelp.queryForbean("select * from Acount where U_ID=93");
	System.out.println(acount.getU_ID());
}
}


转载于:https://my.oschina.net/zhangjie9142/blog/229391

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值