在做web开发时遇到一个事情:
需要从mysql数据表中查询数据并遍历查询结果
这样最简单的方式是:查询到结果根据表中字段列表的顺序来一个个获取字段,但这样需要记住字段的顺序,操作起来不是那么方便。因此便想可不可以把查询结果
ResultSet转化成java的实例对象,然后利用类对象的get方法,这样会方便清晰很多。
查了下,有很多可以参考,于是参考着有了自己的代码,如下:
1.mapper函数:
package com.alibaba.search.offline.oddiff.service;
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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jcraft.jsch.Logger;
//import com.alibaba.druid.sql.ast.statement.SQLCreateViewStatement.Column;
public class OddiffResultSetMapper<T> {
protected static Log logger = LogFactory.getLog(OddiffResultSetMapper.class);
@SuppressWarnings("unchecked")
public List<T> mapRersultSetToObject(ResultSet rs, Class outputClass) {
List<T> outputList = null;
try {
// make sure resultset is not null
if (rs != null) {
logger.info("rs:"+rs);
// 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);
logger.info("columnName:"+columnName+",value:"+columnValue);
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 {
logger.info("rs is null");
return null;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return outputList;
}
}
2.类对象的声明:
package com.alibaba.search.offline.oddiff.service;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
@Entity
public class OddiffEntity {
@Column(name="id")
private Integer Id;
@Column(name="user_name")
private String userName;
@Column(name="app_name")
private String appName;
@Column(name="online_version")
private String onlineVersion;
@Column(name="oa_version")
private String oaVersion;
@Column(name="data_name")
private String dataName;
@Column(name="start_time")
private String startTime;
@Column(name="end_time")
private String endTime;
@Column(name="commit_time")
private String commitTime;
@Column(name="duration_time")
private String durationTime;
@Column(name="status")
private String status;
@Column(name="log_file")
private String logFile;
public void setId(Integer id) {
this.Id = id;
}
public Integer getId() {
return Id;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getAppName() {
return appName;
}
public void setOnlineVersion(String onlineVersion) {
this.onlineVersion = onlineVersion;
}
public String getOnlineVersion() {
return onlineVersion;
}
public void setOaVersion(String oaVersion) {
this.oaVersion = oaVersion;
}
public String getOaVersion() {
return this.oaVersion;
}
public void setDataName(String dataName) {
this.dataName = dataName;
}
public String getDataName() {
return dataName;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getStartTime() {
return startTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getEndTime() {
return endTime;
}
public void setCommitTime(String commitTime) {
this.commitTime = commitTime;
}
public String getCommitTime() {
return commitTime;
}
public void setDurationTime(String durationTime) {
this.durationTime = durationTime;
}
public String getDurationTime() {
return durationTime;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
public void setLogFile(String logFile) {
this.logFile = logFile;
}
public String getLogFile() {
return logFile;
}
@Override
public String toString() {
return "id: " + Id + "\n" +
"user_name: " + userName + "\n"+
"app_name: " + appName + "\n" ;
}
}
3.真的转化:
public static List<OddiffEntity> Execute_select(Connection conn, String sql) {
if (conn==null)
conn = getConn();//此处为通过自己写的方法getConn()获得连接
OddiffResultSetMapper<OddiffEntity> resultSetMapper = new OddiffResultSetMapper<OddiffEntity>();
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
logger.info("---sql:"+sql);
logger.info("select result:"+rs.getFetchSize());
List<OddiffEntity> pojoList = resultSetMapper.mapRersultSetToObject(rs, OddiffEntity.class);
if (pojoList!=null){
for (OddiffEntity job:pojoList){
logger.info("job:"+job.toString());
}
}
return pojoList;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}