如何把ResultSet转换成Java对象

简介:     有时候我们不想使用任何框架,但又需要用JDBC实现类似于iBATIS的orm映射功能,把一个ResultSet转换成我们的JavaBeans,我们可以模仿iBATIS的方式自己写一个ResultSetMapper实现类,利用反射原理把ResultSet转换成一个JavaBeans,下面是网上的一个开源实现,主要用到的是注解和反射机制,我们先看一下使用效果: package c
    有时候我们不想使用任何框架,但又需要用JDBC实现类似于iBATIS的orm映射功能,把一个ResultSet转换成我们的JavaBeans,我们可以模仿iBATIS的方式自己写一个ResultSetMapper实现类,利用反射原理把ResultSet转换成一个JavaBeans,下面是网上的一个开源实现,主要用到的是 注解反射机制,我们先看一下使用效果:
package com.heaven.mapper;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class SampleMain {
		public static void main(String ...args){
		try {
			ResultSetMapper<SamplePojo> resultSetMapper = new ResultSetMapper<SamplePojo>();
			ResultSet resultSet = null;
			// simple JDBC code to run SQL query and populate resultSet - START
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			String database = "jdbc:odbc:AkDb"; 
			Connection connection = DriverManager.getConnection( database ,"","");
			PreparedStatement statement = connection.prepareStatement("SELECT * FROM UsersSample");
			resultSet = statement.executeQuery();
			/******************************/
			List<SamplePojo> pojoList = resultSetMapper.mapRersultSetToObject(resultSet, SamplePojo.class);
			/******************************/
			if(pojoList != null){
				for(SamplePojo pojo : pojoList){
					System.out.println(pojo);
				}
			}else{
				System.out.println("ResultSet is empty. Please check if database table is empty");
			}
			connection.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		}
}
    如上图所示,把ResultSet转换成我们的JavaPojo对象只需要调用ResultSetMapper的一个方法即可完成,使用起来非常方便。
    下面是 ResultSetMapper源代码:
package com.heaven.mapper;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import org.apache.commons.beanutils.BeanUtils;

public class ResultSetMapper<T> {
	@SuppressWarnings("unchecked")
	public List<T> mapRersultSetToObject(ResultSet rs, Class outputClass) {
		List<T> outputList = null;
		try {
			// make sure resultset is not null
			if (rs != null) {
				// check if outputClass has 'Entity' annotation
				if (outputClass.isAnnotationPresent(Entity.class)) {
					// get the resultset metadata
					ResultSetMetaData rsmd = rs.getMetaData();
					// get all the attributes of outputClass
					Field[] fields = outputClass.getDeclaredFields();
					while (rs.next()) {
						T bean = (T) outputClass.newInstance();
						for (int _iterator = 0; _iterator < rsmd.getColumnCount(); _iterator++) {
							// getting the SQL column name
							String columnName = rsmd.getColumnName(_iterator + 1);
							// reading the value of the SQL column
							Object columnValue = rs.getObject(_iterator + 1);
							// iterating over outputClass attributes to check if
							// any attribute has 'Column' annotation with
							// matching 'name' value
							for (Field field : fields) {
								if (field.isAnnotationPresent(Column.class)) {
									Column column = field.getAnnotation(Column.class);
									if (column.name().equalsIgnoreCase(columnName) && columnValue != null) {
										BeanUtils.setProperty(bean, field.getName(), columnValue);
										break;
									}
								}
							}
						}
						if (outputList == null) {
							outputList = new ArrayList<T>();
						}
						outputList.add(bean);
					}

				} else {
					// throw some error
				}
			} else {
				return null;
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return outputList;
	}
}
    使用注解的pojo对象:
<pre name="code" class="java">package com.heaven.mapper;
import javax.persistence.Column;
import javax.persistence.Entity;
@Entity
public class SamplePojo {
	@Column(name="User_Id")
	private int id;
	@Column(name="User_Name")
	private String name;
	@Column(name="Address")
	private String address;
	@Column(name="Gender")
	private boolean gender;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public boolean isGender() {
		return gender;
	}
	public void setGender(boolean gender) {
		this.gender = gender;
	}
	
	@Override
	public String toString() {
		return 	"id: " + id + "\n" + 
				"name: " + name + "\n"+
				"address: " + address + "\n" +
				"gender: " + (gender ? "Male" : "Female") + "\n\n";
	}
}


 
 


目录
相关文章
|
druid Java 数据库连接
java报错Error attempting to get column ‘XXX’ from result set. Cause: java.sql.怎么解决?
java报错Error attempting to get column ‘XXX’ from result set. Cause: java.sql.怎么解决?
2542 0
java报错Error attempting to get column ‘XXX’ from result set. Cause: java.sql.怎么解决?
Java.sql.SQLException: Illegal operation on empty result set.
Java.sql.SQLException: Illegal operation on empty result set.
276 0
|
Java 关系型数据库 MySQL
java.sql.SQLException: Streaming result set com.mysql.jdbc.RowDataDynamic@27ce24aa is still active
java.sql.SQLException: Streaming result set com.mysql.jdbc.RowDataDynamic@27ce24aa is still active
416 0
|
Java 数据库连接
java使用jdbc连接ResultSet通过next()取不到第一条数据
java使用jdbc连接ResultSet通过next()取不到第一条数据
325 0
|
JSON Java 数据库
Java数据库ResultSet转json实现
现在有很多json相关的Java工具,如json-lib、gson等,它们可以直接把JavaBean转换成json格式。 在开发中,可能会从数据库中获取数据,希望直接转成json数组,中间不通过bean。
2022 0
|
SQL Java 数据库连接
|
SQL 关系型数据库 MySQL
让java从Mysql返回多个ResultSet
首先,JDBC对于SQLSERVER来说默认是支持返回,但对于MySql来说,只默认支持存储过程返回多个ResultSet,那对于手写SQL怎么办。 其实很简单,只要一个在连接字符串中加一个参数:allowMultiQueries=true。
1272 0