好东西,万能dao查询,根据sql语句与javabean类自动赋
admin 发布于:2009-11-14 22:55:00
阅读:loading
public class TestSelect {
/**
* 给定一个SQL语句,给定一个javabean返回一个封装好数据的arrayList
*
* @param sql
* @param className
* @return
* @throws Exception
*/
public ArrayList select(String sql, String className) throws Exception {
ArrayList array = new ArrayList();
Connection conn = DBManager.getConnection();
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery(sql);
Object obj = null;
ResultSetMetaData rsmd = rs.getMetaData();// 获得元数据
int columnCount = rsmd.getColumnCount();// 获得sql查询返回的列数个数
while (rs != null && rs.next()) {
obj = Class.forName(className).newInstance();
// 循环设置该类的set方法的相关属性
for (int i = 1; i <= columnCount; i++) {
Method method = obj.getClass()
.getMethod(
getSetMethodName(rsmd.getColumnName(i)),
new Class[] { Class.forName(rsmd
.getColumnClassName(i)) });
method.invoke(obj,
new Object[] { rs.getObject(rsmd.getColumnName(i)) });
}
array.add(obj);
}
rs.close();
stat.close();
conn.close();
return array;
}
/**
* 根据某一个列名,构造set列名方法
*
* @param columnName
* @return
*/
public static String getSetMethodName(String columnName) {
return "set" + columnName.substring(0, 1).toUpperCase()
+ columnName.toLowerCase().substring(1);
}
public static void main(String[] args) throws Exception {
TestSelect dao = new TestSelect();
ArrayList list = dao.select("select * from testselect",
"com.test.test.pub.TestSelectBean");
for (Iterator iter = list.iterator(); iter.hasNext();) {
TestSelectBean bean = (TestSelectBean) iter.next();
System.out.println(bean.getTestid() + "==" + bean.getTestname());
}
}
}
原理就不用说了,用于多表查询的时候,还是一样,只要能保证符合条件就行了。条件是什么呢?你说吧,看看吧
点赞