How to convert ResultSet to Java objects

Source: Internet
Author: User

sometimes we don't want to use any framework, but we need The JDBC implementation is similar to Ibatis's ORM mapping function, transforms a resultset into our javabeans, we can imitate the ibatis way oneself writes a resultsetmapper realization class, Using the principle of reflection to convert resultset into a JavaBeans, the following is an open-source implementation of the Internet, the main use is AnnotationsAnd ReflectionMechanism, let's look at the use effect:
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 Re Sultsetmapper<samplepojo> (); ResultSet ResultSet = null;//Simple JDBC code to run SQL query and populate Resultset-startclass.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 the database table is empty "); Connection.close ();} catch (ClassNotFoundException e) {e.printstacktrace ();} catch (SQLException e) {e.printstacktrace ()}}}
As shown, converting resultset to our Javapojo object requires only one method of calling Resultsetmapper, which is very convenient to use.Below isresultsetmapper Source code:
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 nullif (rs! = null) {//Check if Outputclass has ' Entity ' annotationif (outputclass.isannotationpre Sent (Entity.class)) {//Get the resultset metadataresultsetmetadata RSMD = Rs.getmetadata ();//Get all the attributes of O utputclassfield[] fields = Outputclass.getdeclaredfields (), while (Rs.next ()) {T bean = (T) outputclass.newinstance (); for (int _iterator = 0; _iterator < Rsmd.getcolumncount (); _iterator++) {//Getting the SQL column Namestring columnName = rsmd.getcolumnname (_iterator + 1);//reading the value of the SQL columnobject Columnvalu E = Rs.getobject (_iterator + 1);//iterating over Outputclass attributes to check if//any attribute have ' Column ' Annotati On with//matching ' name ' valuefor (Field field:fields) {if (Field.isannotationpresent (Column.class)) {Column Column = f Ield.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 objects that use annotations:
<pre name= "code" class= "java" >package com.heaven.mapper;import Javax.persistence.column;import javax.persistence.Entity; @Entitypublic 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 ;p ublic 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;} @Overridepublic String toString () {return ID: "+ id +" \ n "+" name: "+ name +" \ n "+" Address: "+ address +" \ n "+" Gende R: "+ (gender?") Male ":" Female ") +" \ n ";}}





How to convert ResultSet to Java objects

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.