`
love19820823
  • 浏览: 935397 次
文章分类
社区版块
存档分类
最新评论

ResultSet转为实体对象

 
阅读更多
package org.test;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
* <p>
* Title: LoonFramework
* </p>
* <p>
* Description:
* </p>
* <p>
* Copyright: Copyright (c) 2007
* </p>
* <p>
* Company: LoonFramework
* </p>
*
* @author chenpeng
* @email:ceponline@yahoo.com.cn
* @version 0.1
*/
public class ConnectionTest {

/**
* 匹配指定class中数据,并返回包含get和set方法的object
*
* @author chenpeng
* @param clazz
* @param beanProperty
* @return
*/
private Object[] beanMatch(Class clazz, String beanProperty) {
Object[] result = new Object[2];
char beanPropertyChars[] = beanProperty.toCharArray();
beanPropertyChars[0] = Character.toUpperCase(beanPropertyChars[0]);
String s = new String(beanPropertyChars);
String names[] = { ("set" + s).intern(), ("get" + s).intern(),
("is" + s).intern(), ("write" + s).intern(),
("read" + s).intern() };
Method getter = null;
Method setter = null;
Method methods[] = clazz.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
// 只取公共字段
if (!Modifier.isPublic(method.getModifiers()))
continue;
String methodName = method.getName().intern();
for (int j = 0; j < names.length; j++) {
String name = names[j];
if (!name.equals(methodName))
continue;
if (methodName.startsWith("set")
|| methodName.startsWith("read"))
setter = method;
else
getter = method;
}
}
result[0] = getter;
result[1] = setter;
return result;
}

/**
* 为bean自动注入数据
*
* @author chenpeng
* @param object
* @param beanProperty
*/
private void beanRegister(Object object, String beanProperty, String value) {
Object[] beanObject = beanMatch(object.getClass(), beanProperty);
Object[] cache = new Object[1];
Method getter = (Method) beanObject[0];
Method setter = (Method) beanObject[1];
try {
// 通过get获得方法类型
String methodType = getter.getReturnType().getName();
if (methodType.equalsIgnoreCase("long")) {
cache[0] = new Long(value);
setter.invoke(object, cache);
} else if (methodType.equalsIgnoreCase("int")
|| methodType.equalsIgnoreCase("integer")) {
cache[0] = new Integer(value);
setter.invoke(object, cache);
} else if (methodType.equalsIgnoreCase("short")) {
cache[0] = new Short(value);
setter.invoke(object, cache);
} else if (methodType.equalsIgnoreCase("float")) {
cache[0] = new Float(value);
setter.invoke(object, cache);
} else if (methodType.equalsIgnoreCase("double")) {
cache[0] = new Double(value);
setter.invoke(object, cache);
} else if (methodType.equalsIgnoreCase("boolean")) {
cache[0] = new Boolean(value);
setter.invoke(object, cache);
} else if (methodType.equalsIgnoreCase("java.lang.String")) {
cache[0] = value;
setter.invoke(object, cache);
} else if (methodType.equalsIgnoreCase("java.io.InputStream")) {
} else if (methodType.equalsIgnoreCase("char")) {
cache[0] = (Character.valueOf(value.charAt(0)));
setter.invoke(object, cache);
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 转换connection查询结果为指定对象实体集合。
*
* @author chenpeng
* @param connection
* @param clazz
* @param sql
* @return
*/
public Collection get(final Connection connection, final Class clazz,
final String sql) {
// 创建PreparedStatement
PreparedStatement ptmt = null;
// 创建resultset
ResultSet rset = null;
// 创建collection
Collection collection = null;
try {
// 赋予实例
ptmt = connection.prepareStatement(sql);
rset = ptmt.executeQuery();
collection = get(rset, clazz);
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
try {
// 关闭rs并释放资源
if (rset != null) {
rset.close();
rset = null;
}
// 关闭ps并释放资源
if (ptmt != null) {
ptmt.close();
ptmt = null;
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
return collection;
}

public Collection get(final ResultSet result, final Class clazz) {
// 创建collection
Collection collection = null;
try {
ResultSetMetaData rsmd = result.getMetaData();
// 获得数据列数
int cols = rsmd.getColumnCount();
// 创建等同数据列数的arraylist类型collection实例
collection = new ArrayList(cols);
// 遍历结果集
while (result.next()) {
// 创建对象
Object object = null;
try {
// 从class获得对象实体
object = clazz.newInstance();
} catch (Exception e) {
}
// 循环每条记录
for (int i = 1; i <= cols; i++) {
beanRegister(object, rsmd.getColumnName(i), result
.getString(i));
}
// 将数据插入collection
collection.add(object);
}
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {

}
return collection;
}

public static void main(String[] args) {
try {
Class.forName("org.gjt.mm.mysql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true";
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
connection = DriverManager.getConnection(url, "root", "xxxx");
ConnectionTest test = new ConnectionTest();
// Ltest是我测试用类,实际操作请注入相关对象,支持set,get,is,read,writer为前缀数据对,更多请继续添加。
Collection collection = test.get(connection, Ltest.class,
"select * from ltest");
for (Iterator it = collection.iterator(); it.hasNext();) {
Ltest ltest = (Ltest) it.next();
System.out.println(ltest.getId() + ":" + ltest.getName());
}
}
// SQL异常,用于抛出SQL语句处理中所引发的错误。
catch (SQLException e) {
System.err.println(e.getMessage());
}
// finally,此标识用以包含必须访问的内容。
finally {
try {
// 关闭rs并释放资源
if (rs != null) {
rs.close();
rs = null;
}
// 关闭ps并释放资源
if (ps != null) {
ps.close();
ps = null;
}
// 关闭connection并释放资源
if (connection != null) {
connection.close();
connection = null;
}
// 如果关闭时产生异常将由此抛出
} catch (SQLException e) {
System.err.println(e.getMessage());
}

}
}
}
________________________
前一阵写loonframework-db时,写过类似的处理方法,只不过为了效率我都是直接操作的数组对象,现改为集合对象,减少了一些处理,但大体流 程如此。我框架中cache一直没有做完,所以没有为您添加,您可以用map之类做一个简单的cache来使用,目前万条数据会较慢于 ResultSet,但是可以正常使用。

更多方法,请见http://looframework.sourceforge.net/或http://www.open-open.com/open198258.htm

国产JAVA游戏开源框架Loonframework 这是一个基于Java技术的2D游戏框架,将涉及J2SE,J2ME,JavaFX三个方面。开发目的在于以脚本化的方式,快速的开发可跨平台移植的 Java游戏。并且它本身也是一个持久层框架,能在框架内最大限度的满足用户需求。目前展示了一个仿梦幻模拟战世界观的AVG+SLG脚本,以 Applet方式展示在looframework.sourceforge.net上运行,也可以下载此Jar包后双击运行。由于是采用Graphics 直接绘制界面,所以仅使用了最基础的AWT作为表示,有很好的移植可能性。功能上,采用脚本方式动态生成界面与对话情节,重用可行性高。 项目潜力上,随着日后JavaFX技术的改进与普及,本项目还会有一次质上的飞跃。在WEB2.0概念深入人心,如猫游记等AJAX游戏都能够有人去玩的 今天,利用JAVA开发的平台无视,且能如RMXP由普通用户即可制作的游戏框架 (而且,利用Java特性,完全可以做到由用户通过网页定制游戏并展示,甚至可以考虑提供一个类似于土豆的平台,用以展示用户DIY自己的游戏或相关图形 资源。)
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics