Saturday, May 29, 2010

Part III : A Simple and Smart Result Mapper

Now a days we make extensive use of Annotations. Whether it is a good or bad practice to mix configuration meta data with code is debatable, but its better than proprietary XML tags. Since we are so used to mixing meta data in our Java code, why not make use of same tactics in building our data mapper.
SQL statements in all databases supports something called an alias for column names. I will use this to map a SQL result column to a property in my bean. This is better because even if my column name changes but my alias remains same my bean will be populated properly.
I use JODD bean utils. You can download the JODD distribution here.  A problem with JODD is that it is not available in any of the global maven repositories. So you need install the same in your local repository by running the following command 
C:\>mvn install:install-file -Dfile=jodd-3.0.9.jar  -DgroupId=jodd -DartifactId=
jodd -Dversion=3.0.9 -Dpackaging=jar 
Use the GUI screens if you are using Archiva repository manager. 
I am on windows and I have kept my jar is located at C:\jodd-3.0.9.jar. It has no other dependencies. 

Correction - As pointed out below in the comments section JODD is now available on Maven.

<dependency>
    <groupId>org.jodd</groupId>
    <artifactId>jodd-wot</artifactId>
    <version>3.1.0</version>
</dependency>



Here is the modified abstract dao support class.
package net.breezeware.spring.dao;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import jodd.bean.BeanUtil;


import org.apache.commons.lang.reflect.ConstructorUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

/**
* @author dhrubo
*
*/
public abstract class AbstractBaseDaoSupport extends SimpleJdbcDaoSupport{
private Logger logger = LoggerFactory.getLogger(AbstractBaseDaoSupport.class);

private Map<String, String> sqlMap;


protected List<?> queryForList(String id, Class primaryType, Object ...params) {
String sql = sqlMap.get(id);
List<Map<String, Object>> mappedResultList = this.getSimpleJdbcTemplate().queryForList(sql, params);

return this.preapreList(mappedResultList, primaryType);
}

protected List<?> queryForList(String id, Class primaryType) {
List<Object> result = new ArrayList<Object>();
String sql = sqlMap.get(id);

List<Map<String, Object>> mappedResultList = this.getSimpleJdbcTemplate().queryForList(sql, new HashMap());
return this.preapreList(mappedResultList, primaryType);
}


protected Object queryForObject(String id, Class type, Object ...params) {
String sql = sqlMap.get(id);
Map<String, ?> dataMap = this.getSimpleJdbcTemplate().queryForMap(
sql, params);

return prepareObject(dataMap,type);
}

protected void insert(String id, Object ...params ) {
String sql = sqlMap.get(id);
this.getSimpleJdbcTemplate().update(sql, params);
}

private List<?> preapreList(List<Map<String, Object>> mappedResultList,Class primaryType) {
List<Object> result = new ArrayList<Object>();
Object holder = null;
for(Map<String, Object> resultMap : mappedResultList) {
holder = prepareObject(resultMap,primaryType);
result.add(holder); 
}

return result;
}
private Object prepareObject(Map<String, ?> resultMap, Class primaryType) {
Iterator<String> it = resultMap.keySet().iterator();
Object holder = getNewObjectInstance(primaryType);

String name = null;
Object value = null;

//set all the properties
while(it.hasNext()) {


name = it.next();
value = resultMap.get(name);

logger.debug("Mapping property = {}, value = {}",name,value);

BeanUtil.setPropertyForcedSilent(holder, name, value);
}

return holder;

}



private Object getNewObjectInstance(Class clazz) {
Object object = null;
try {
object = ConstructorUtils.invokeExactConstructor(clazz, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
return object;
}

/**
* @param sqlMap the sqlMap to set
*/
public void setSqlMap(Map<String, String> sqlMap) {
this.sqlMap = sqlMap;
}


}




This class is by no means complete and is evolving. But it has the essential methods to get the ball rolling. This class uses the Spring JDBC to execute the SQL statements. The SQL statements are picked up from the externalized cache. It utilizes the meta data or column names in the SQL result set retrieved and populated by Spring JDBC as keys in those row maps. Note that in case a column does not have corresponding bean property, it will escape silently. With smart configuration (will show examples soon), this can support nested properties.

2 comments:

  1. Starting from 3.1.0, Jodd is available on Maven;)

    ReplyDelete
  2. This is generally a wonderful website i should say,I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and really amazing and impressive website design.

    ReplyDelete