将ResultSet中得到的一行或多行结果集封装成对象的实例

网友投稿 418 2023-06-07

将ResultSet中得到的一行或多行结果集封装成对象的实例

将ResultSet中得到的一行或多行结果集封装成对象的实例

首先说一下这个使用场景,我们在使用jdbc连接数据库的时候,执行查询语句时候会得到一个结果集,如果想要再获取这个结果集中的值,就需要我们GICzBLawcj将他转换成一个对象,然后通过对象的get和set方法来获取到数据库中的值。

public class BaseDao {

private Class> cls;

public BaseDao() {

//得到父类的泛型

Type sType=getClass().getGenericSuperclass();

//得到实际的类型参数数组

Type[] generics=((ParameterizedType) sType).getActualTypeArguments();

//得到第一个泛型的Class

cls=(Class>) (generics[0]);

}

/**

* 单表多条查询,将查询到的多条记录传入一个对象,http://然后再将这些存入一个集合中,返回这个集合

* @param sql 传入对应的sql查询语句

* @param parameters 传入对应的占位符的值

* @return 返回查询到的记录转化成的对象的集合

*/

//Object...parameters是sql语句中对应的占位符的值,是一个不定长可变参数,我们需要写一个函数来获取他

public List list(String sql,Object...parameters) {

Connection conn = null;

PreparedStatement st = null;

ResultSet rs = null;

List list = new ArrayList<>();

try {

conn = JdbcUtil.getConnection();

st = conn.prepareStatement(sql);

setParameters(st, parameters);

rs = st.executeQuery();

while(rs.next()) {

//将获取到的结果集存入一个对象中,这个我们也单独写一个函数来实现

E obj = oneRowToObject(rs);

//然后将对象存入一个集合中返回

list.add(obj);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

JdbcUtil.closeAll(rs, st, conn);

}

return list;

}

首先来写一下获取不定长可变参数的方法

/**

* 设置占位符

* @param st 预处理

* @param parameters 占位符数组

* @return 返回存储占位符对应的对象的数组

*/

private void setParameters(PreparedStatement st, Object[] parameters) {

//判断是否有结果集,结果集中是否有记录

if(parameters!=null&&parameters.length>0) {

for(int i=0;i

try {

st.setObject(i+1,parameters[i] );

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

然后再把一个结果集转化成一个对象的方法写一下

* 把得到的一列数据存入到一个对象中

* @param rs

* @return

* @throws InstantiationException

* @throws IllegalAccessException

* @throws SQLException

* @throws NoSuchMethodException

* @throws SecurityException

* @throws IllegalArgumentException

* @throws InvocationTargetException

*/

@SuppressWarnings("unchecked")

private E oneRowToObject(ResultSet rs) throws InstantiationException, IllegalAccessException, SQLException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {

E obj;

obj=(E) cls.newInstance();

//获取结果集元数据(获取此 ResultSet 对象的列的编号、类型和属性。)

ResultSetMetaData rd=rs.getMetaData();

for (int i = 0; i < rd.getColumnCount(); i++) {

//获取列名

String columnName=rd.getColumnLabel(i+1);

//组合方法名

String methodName="set"+columnName.substring(0, 1).toUpperCase()+columnName.substring(1);

//获取列类型

int columnType=rd.getColumnType(i+1);

Method method=null;

switch(columnType) {

case java.sql.Types.VARCHAR:

case java.sql.Types.CHAR:

method=cls.getMethod(methodName, String.class);

if(method!=null) {

method.invoke(obj, rs.getString(columnName));

}

break;

case javaGICzBLawcj.sql.Types.INTEGER:

case java.sql.Types.SMALLINT:

method=cls.getMethod(methodName, int.class);

if(method!=null) {

method.invoke(obj, rs.getInt(columnName));

}

break;

case java.sql.Types.BIGINT:

method=cls.getMethod(methodName, long.class);

if(method!=null) {

method.invoke(obj, rs.getLong(columnName));

}

break;

case java.sql.Types.DATE:

case java.sql.Types.TIMESTAMP:

try {

method=cls.getMethod(methodName, Date.class);

if(method!=null) {

method.invoke(obj, rs.getTimestamp(columnName));

}

} catch(Exception e) {

method=cls.getMethod(methodName, String.class);

if(method!=null) {

method.invoke(obj, rs.getString(columnName));

}

}

break;

case java.sql.Types.DECIMAL:

method=cls.getMethod(methodName, BigDecimal.class);

if(method!=null) {

method.invoke(obj, rs.getBigDecimal(columnName));

}

break;

case java.sql.Types.DOUBLE:

case java.sql.Types.NUMERIC:

method=cls.getMethod(methodName, double.class);

if(method!=null) {

method.invoke(obj, rs.getDouble(columnName));

}

break;

case java.sql.Types.BIT:

method=cls.getMethod(methodName, boolean.class);

if(method!=null) {

method.invoke(obj, rs.getBoolean(columnName));

}

break;

default:

break;

}

}

return obj;

}

使用的话就是写一个实体类Dao继承BaseDao

public class UserDao extends BaseDao {

}

测试一下:

public class test {

public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, SQLException, IntrospectionException {

UserDao userdao = new UserDao();

List list=userdao.list("select * from user");

System.out.println("uid\t"+"uname\t"+"state\t"+"flag");

for (User user : list) {

System.out.println(user.getUid()+"\t"+user.getUname()+"\t"+user.getState()+"\t"+user.getFlag());

}

}

}

try {

st.setObject(i+1,parameters[i] );

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

然后再把一个结果集转化成一个对象的方法写一下

* 把得到的一列数据存入到一个对象中

* @param rs

* @return

* @throws InstantiationException

* @throws IllegalAccessException

* @throws SQLException

* @throws NoSuchMethodException

* @throws SecurityException

* @throws IllegalArgumentException

* @throws InvocationTargetException

*/

@SuppressWarnings("unchecked")

private E oneRowToObject(ResultSet rs) throws InstantiationException, IllegalAccessException, SQLException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {

E obj;

obj=(E) cls.newInstance();

//获取结果集元数据(获取此 ResultSet 对象的列的编号、类型和属性。)

ResultSetMetaData rd=rs.getMetaData();

for (int i = 0; i < rd.getColumnCount(); i++) {

//获取列名

String columnName=rd.getColumnLabel(i+1);

//组合方法名

String methodName="set"+columnName.substring(0, 1).toUpperCase()+columnName.substring(1);

//获取列类型

int columnType=rd.getColumnType(i+1);

Method method=null;

switch(columnType) {

case java.sql.Types.VARCHAR:

case java.sql.Types.CHAR:

method=cls.getMethod(methodName, String.class);

if(method!=null) {

method.invoke(obj, rs.getString(columnName));

}

break;

case javaGICzBLawcj.sql.Types.INTEGER:

case java.sql.Types.SMALLINT:

method=cls.getMethod(methodName, int.class);

if(method!=null) {

method.invoke(obj, rs.getInt(columnName));

}

break;

case java.sql.Types.BIGINT:

method=cls.getMethod(methodName, long.class);

if(method!=null) {

method.invoke(obj, rs.getLong(columnName));

}

break;

case java.sql.Types.DATE:

case java.sql.Types.TIMESTAMP:

try {

method=cls.getMethod(methodName, Date.class);

if(method!=null) {

method.invoke(obj, rs.getTimestamp(columnName));

}

} catch(Exception e) {

method=cls.getMethod(methodName, String.class);

if(method!=null) {

method.invoke(obj, rs.getString(columnName));

}

}

break;

case java.sql.Types.DECIMAL:

method=cls.getMethod(methodName, BigDecimal.class);

if(method!=null) {

method.invoke(obj, rs.getBigDecimal(columnName));

}

break;

case java.sql.Types.DOUBLE:

case java.sql.Types.NUMERIC:

method=cls.getMethod(methodName, double.class);

if(method!=null) {

method.invoke(obj, rs.getDouble(columnName));

}

break;

case java.sql.Types.BIT:

method=cls.getMethod(methodName, boolean.class);

if(method!=null) {

method.invoke(obj, rs.getBoolean(columnName));

}

break;

default:

break;

}

}

return obj;

}

使用的话就是写一个实体类Dao继承BaseDao

public class UserDao extends BaseDao {

}

测试一下:

public class test {

public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, SQLException, IntrospectionException {

UserDao userdao = new UserDao();

List list=userdao.list("select * from user");

System.out.println("uid\t"+"uname\t"+"state\t"+"flag");

for (User user : list) {

System.out.println(user.getUid()+"\t"+user.getUname()+"\t"+user.getState()+"\t"+user.getFlag());

}

}

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot docker jenkins 自动化部署并上传镜像的步骤详解
下一篇:Java阻塞队列四组API介绍(小结)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~