您的位置:首页 > 数据库

将普通sql查询的将结果集转换指定的对象,然后对象存在list中并返回

2015-08-28 09:03 501 查看
package com.epsoft.util;
import java.lang.reflect.Method;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 通用查询,将普通sql查询的将结果集转换指定的对象,然后对象存在list中并返回;
* 调用方法:UtilQueryBS.getQueryInfoByManulSQL(sql,Bean)
* 传入值为一个sql字符串,一个要转换的Bean对象(可以是:Bean对象,package包 + Bean类名,Bean.class);
*
* @author wangb2
*
*/
public class UtilQueryObj<T> {

/**
* 查询语句
*/
private String querySQL;

/**
* 数据库连接
*/
private Connection conn;
/**
* 要转换成的Bean对象
*/
private Class<?> cla;
private T obj;
PreparedStatement stmt = null;

/**
* 预编译sql参数表
*/
List<Map<String,String>> e = null;

public UtilQueryObj() {
super();
}
/**
* 执行查询,
*
* @return wangb2
* @throws AppException
*/
@SuppressWarnings("unchecked")
public List<T> query() throws SQLException {
ResultSet rs = null;
ResultSetMetaData rsmd = null;
List<T> list = null;
int cols;
try {
stmt = conn.prepareStatement(querySQL);
if(e==null){
}else{
for (Map<String, String> t : e) {
Integer index =Integer.parseInt(t.get("index").toString());
String type = t.get("type").toString();
String value = t.get("value");

if ( type.equalsIgnoreCase("String")) {
stmt.setString(index, value.toString());
} else if (type.equalsIgnoreCase("Long")) {
stmt.setLong(index, Long.parseLong(value));
} else if (type.equalsIgnoreCase("Double")) {
stmt.setDouble(index, Double.parseDouble(value));
} else if (type.equalsIgnoreCase("Integer") || type.equalsIgnoreCase("int")) {
stmt.setInt(index,Integer.parseInt(value));
} else if (type.equalsIgnoreCase("Boolean")) {
stmt.setBoolean(index,Boolean.parseBoolean(value));
} else if (type.equalsIgnoreCase("Float")) {
stmt.setFloat(index,Float.parseFloat(value));
} else if (type.equalsIgnoreCase("Date")) {
stmt.setDate(index,stringToDate(value));
}
}
}
rs = stmt.executeQuery();
rsmd = rs.getMetaData();
cols = rsmd.getColumnCount();
list = new ArrayList<T>();
/*
* 将每一行的结果集转换成指定类对象
*/
while (rs.next()) {
// 并实例化成对象
obj = (T) cla.newInstance();
for (int j = 1; j <= cols; j++) {
String colName = iniStr((rsmd.getColumnName(j)).toLowerCase());
try{
// 通过getter确定bean属性的数据类型
Method met = cla.getMethod("get" + colName);
// 取得属性的数据类型
Class<?> p = met.getReturnType();
//获取set
met = obj.getClass().getMethod("set" + colName, p);
// 根据属性的数据类型来判断该用哪种数据类型取值,并将值存入对象属性中
if (p == String.class) {
met.invoke(obj, rs.getString(j));
} else if (p == Long.class || p == long.class) {
met.invoke(obj, rs.getLong(j));
} else if (p == Double.class || p == double.class) {
met.invoke(obj, rs.getDouble(j));
} else if (p == Integer.class || p == int.class) {
met.invoke(obj, rs.getInt(j));
} else if (p == Blob.class) {
met.invoke(obj, rs.getBlob(j));
} else if (p == Boolean.class || p == boolean.class) {
met.invoke(obj, rs.getBoolean(j));
} else if (p == Byte.class || p == byte.class) {
met.invoke(obj, rs.getByte(j));
} else if (p == Short.class || p == short.class) {
met.invoke(obj, rs.getShort(j));
} else if (p == Object.class) {
met.invoke(obj, rs.getObject(j));
} else if (p == Float.class || p == float.class) {
met.invoke(obj, rs.getFloat(j));
} else if (p == java.sql.Date.class) {
met.invoke(obj, rs.getDate(j));
} else if (p == java.util.Date.class) {
met.invoke(obj, rs.getDate(j));
} else if (p == Clob.class) {
met.invoke(obj, rs.getClob(j));
}
}catch (NoSuchMethodException e) {
System.err.println("");
}
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 处理set属性方法名,首字母为大写
*
* @param old
* @return
*/
public String iniStr(String old) {
return old.substring(0, 1).toUpperCase() + old.substring(1);
}

/**
* @param connection
*/
public void setConnection(Connection connection) {
conn = connection;
}
/**
* @param string
*/
public void setQuerySQL(String string) {
querySQL = string;
}
public Class<?> getCla() {
return cla;
}
public void setCla(Class<?> cla) {
this.cla = cla;
}
/**
* 类入口,通过调用,将返回一个list集合 查询的结果集将转换为指定的对象, 结果集对象存入list中返回
*
* @param sql
*            查询的sql语句
* @param cla
*            结果集转换的对象
* @return list
* @throws SQLException
*/
public static<T> List<T> getQueryInfoByManulSQL(String sql, Class<T> cla,Connection connection) throws SQLException {
UtilQueryObj<T> query = new UtilQueryObj<T>();
query.setConnection(connection);
query.setQuerySQL(sql);
query.setCla(cla);
List<T> list = query.query();
return list;
}
/**
* 类入口,通过调用,将返回一个list集合 查询的结果集将转换为指定的对象, 结果集对象存入list中返回
*
* @param sql
*            查询的sql语句
* @param cla
*            结果集转换的对象
* @return list 当使用预编译sql时传入,结构为,List<Map<String,String>>,
*          Map<String,String>中应包含 index 预编译的索引,type 这个值是什么类型的,value 值;可也使用toMap方法组装
*
* @throws SQLException
*/
public static<T> List<T> getQueryInfoByManulSQL(String sql, Class<T> cla,Connection connection,List<Map<String,String>> lp) throws SQLException {
UtilQueryObj<T> query = new UtilQueryObj<T>();
query.setConnection(connection);
query.setQuerySQL(sql);
query.e=lp;
query.setCla(cla);
List<T> list = query.query();
return list;
}
/**
* 类入口,通过调用将返回一个list集合 查询的结果集将转换为指定的对象, 结果集对象存入list中返回
*
* @param sql
*            查询的sql语句
* @param objName
*            结果集转换的对象
* @return list
* @throws SQLException
*/
public static<T> List<T> getQueryInfoByManulSQL(String sql, Object objName,Connection connection) throws SQLException {
UtilQueryObj<T> query = new UtilQueryObj<T>();
query.setConnection(connection);
query.setQuerySQL(sql);
query.setCla(objName.getClass());
List<T> list = query.query();
return list;
}
/**
* 类入口,通过调用将返回一个list集合 查询的结果集将转换为指定的对象, 结果集对象存入list中返回
*
* @param sql
*            查询的sql语句
* @param className
*            结果集转换的对象
* @return list
* @throws ClassNotFoundException
* @throws SQLException
*/
public static<T> List<T> getQueryInfoByManulSQL(String sql, String className,Connection connection) throws
ClassNotFoundException, SQLException {
UtilQueryObj<T> query = new UtilQueryObj<T>();
query.setConnection(connection);
query.setQuerySQL(sql);
query.setCla(Class.forName(className));
List<T> list = query.query();
return list;
}
/**
*
* @param index 预编译的索引
* @param type 这个值是什么类型的
* @param value 值
* @return
*/
public static Map<String,String> toMap(String index,String type,String value){
Map<String,String> map = new HashMap<String,String>();
map.put("index", index);
map.put("type", type);
map.put("value", value);
return map;

}

public static java.sql.Date stringToDate(String str) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
java.util.Date d = sdf.parse(str);
return new java.sql.Date(d.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

本文出自 “闲书” 博客,请务必保留此出处http://wangler.blog.51cto.com/4529534/1689152
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: