Click here to Skip to main content
13,355,335 members (69,829 online)
Click here to Skip to main content
Add your own
alternative version


6 bookmarked
Posted 24 Apr 2012

Mapping JDBC ResultSet to Object using Annotations

, 24 Apr 2012
Rate this:
Please Sign up or sign in to vote.
A simple code to map JDBC ResultSet to an Object using Annotations in a generic way


This tip demonstrates how JDBC ResultSet can be mapped to an Object using Annotations


This tip uses Annotations and Reflection. So a basic knowledge of these will be helpful. 

Using the code  

First we need an Annotated POJO (Plain Old Java Object) to hold values retrieved in ResultSet

The attribute name can be anything, the annotation 'column' specifies the SQL column name. The annotation 'Entity' is required to mark the class capable of hold database values

Below is a

import javax.persistence.Column;
import javax.persistence.Entity;

public class SamplePojo {
	private int id;
	private String name;
	private String address;
	private boolean gender;
	public int getId() {
		return id;
	public void setId(int id) { = id;
	public String getName() {
		return name;
	public void setName(String 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;
	public String toString() {
		return 	"id: " + id + "\n" + 
				"name: " + name + "\n"+
				"address: " + address + "\n" +
				"gender: " + (gender ? "Male" : "Female") + "\n\n";

Code to map ResultSet to Object -

 Below is the code that maps the ResultSet to an Object of this SamplePojo and returns ArrayList containing SamplePojo objects  

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> {
	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 ( {
						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
									if (
											&& columnValue != null) {
										BeanUtils.setProperty(bean, field
												.getName(), columnValue);
						if (outputList == null) {
							outputList = new ArrayList<T>();

				} else {
					// throw some error
			} else {
				return null;
		} catch (IllegalAccessException e) {
		} catch (SQLException e) {
		} catch (InstantiationException e) {
		} catch (InvocationTargetException e) {
		return outputList;

The function  mapRersultSetToObject maps resultset to an ArrayList of type SamplePojo.  It first checks if the outputClass has the 'Entity' annotation. The core logic of this function is that, it gets the attributes in the outputClass having annotation 'Column'. If this attribute has the 'Column' annotation with 'name' value same as that of SQL column name, the value of the SQL column is set to the current attribute in outputClass.

Using the ResultSetMapper class 

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
		String database = "jdbc:odbc:AkDb"; 
		Connection connection = DriverManager.getConnection( database ,"","");
		PreparedStatement statement = connection.prepareStatement("SELECT * FROM UsersSample");
		resultSet = statement.executeQuery();
		// simple JDBC code to run SQL query and populate resultSet - END
		List<SamplePojo> pojoList = resultSetMapper.mapRersultSetToObject(resultSet, SamplePojo.class);
		// print out the list retrieved from database
		if(pojoList != null){
			for(SamplePojo pojo : pojoList){
			System.out.println("ResultSet is empty. Please check if database table is empty");
	} catch (ClassNotFoundException e) {
	} catch (SQLException e) {

Points of Interest 

Without using any framework (ibatis/hibernate etc), the pain of mapping individual columns from ResultSet can be avoided. If you want to map more columns, just add more attributes to the POJO, annotate them with correct column names and you are done !

 If the query is complex, may be very complex containing lot of joins on lot of columns, just use SQL alias to rename each column with a unique name and use this column alias while annotating the POJO

Please feel free to share your comments, complements or complaints.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Web Developer
India India
No Biography provided

You may also be interested in...


Comments and Discussions

Questionabout @Entity annotation Pin
Member 950131713-Jul-15 21:48
memberMember 950131713-Jul-15 21:48 
Questionusing this with gwt (&maven) Pin
Thomas Käfer26-Apr-15 22:40
memberThomas Käfer26-Apr-15 22:40 
Generalnice work Pin
John Michelau22-Oct-13 15:38
memberJohn Michelau22-Oct-13 15:38 
Questionannotations Pin
Member 1032761910-Oct-13 2:38
memberMember 1032761910-Oct-13 2:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180111.1 | Last Updated 24 Apr 2012
Article Copyright 2012 by AprNgp
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid