ResultSet Convert to Java class object

Source: Internet
Author: User

When doing web development, you encounter a thing:

Need to query data from a MySQL data table and traverse query results

The simplest way to do this is to query the results to get the fields in the order of the list of fields in the table, but it is not convenient to remember the order of the fields. So I was wondering if we could get the query results

The resultset translates into Java instance objects and then takes advantage of the get method of the class object, which makes it much easier to be clear.

Check the next, there are many can refer to, so the reference to have their own code, as follows:

1.mapper function:

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 are 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. Declaration of the class object:

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. True conversions:

public static list<oddiffentity> Execute_select (Connection conn, String sql) {

if (conn==null)

conn = Getconn ();//Here is a way to get a connection by writing your own 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;

}

ResultSet Convert to Java class object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.