Skip to main content

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.

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

Post a Comment

Popular posts from this blog

CKEDITOR 3.x - Simplest Ajax Submit Plugin

  I have assumed that you have downloaded and got started with CKEDITOR. Step 1 – The html file is shown below: <html> <head> <title>Writer</title> <meta content="text/html; charset=utf-8" http-equiv="content-type" /> <script type="text/javascript" src="ckeditor/ckeditor.js"></script> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <style> .cke_contents { height: 400px !important; } </style> </head> <body> <form action="sample_posteddata.php" method="post"> <textarea id="editor" > </textarea> <script type="text/javascript"> //<![CDATA[ CKEDITOR.replace( 'editor', { fullPage : true, uiColor : '#9AB8F3', toolbar : 'MyToolbar' }); //]]> </script> </form> </body> </html> Note that the jquery js

Part 3 - Integrating Tiles, Thymeleaf and Spring MVC 3

In this post I will demonstrate how to integrate Apache Tiles with Thymeleaf. This is very simple. The first step is to include the tiles and thymeleaf-tiles extension dependencies. I will include them in the pom.xml. Note we wil lbe using Tiles 2.2.2 Listing 1 - parent/pom.xml --- thymeleaf-tiles and tiles dependencies <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- Tiles --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <dependency> <groupId>org.apache.tiles</groupId> <artifactId>tiles-core</artifactId> <version>${tiles.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.tiles</groupId> <artifactId>tiles-template</artifactId> <version>${tiles.version}</version> <scope>compile</s

How to Stand up a Spring Cloud Config Server?

Setup and Configure Spring Cloud Config Server Project Spring Cloud Config Server is just another Spring Boot application. It provides several infrastructure micro services to centralize access to configuration information backed by a version controlled (well at least in the case of default GIT storage) repository. Step 1 - Create a Spring Boot project in STS with the dependencies shown in Figure 2. Figure 1 - Creating Spring Boot project to setup Spring Cloud Config Server Figure 2 - Spring Cloud Config Server dependencies Click on 'Finish' to complete the creation of the Spring Boot project in STS. The build.gradle file is shown in listing below. There is only one dependency to the Spring Cloud Config Server. Also Spring Cloud release train 'Dalston.SR1'. Step 2 - Annotate the class containing main method The next step is to annotate the ConfigServerInfraApplication class with  @EnableConfigServer That's all is needed on the Java si