Saturday, January 12, 2013

Ibatis return custom java object from query as List

Using IBatis if a sql query returns a number of rows and you need to IBatis to convert these rows to a java Object then you need to

1) create a resultMap entry where you map the propery in the java object to a column in a table
2) create a statement which contains the query and specify a resultMap (This is has been defined by above step 1)

using the above two configurations, Ibatis converts each row into a new MyClass() object and then populates it with the data from that row.

java code snippet
Map parameterMap = new HashMap();
parameterMap.put("inputNames", "abc");
      
List nameList = (List) getSqlMapClientTemplate().queryForList("getEmpDetails", parameterMap);
       
 

ibatis config       
<sqlMap namespace="myQueries">

    <resultMap id="idMap" class="com.test.MyClass">
        <result property="myId" column="ID_COLUMN_IN_DATABASE_TABLE"/>
        <result property="name" column="NAME_COLUMN_IN_DATABASE_TABLE"/>
    </resultMap>
   
    <statement id="getEmpDetails" resultMap="idMap"
        parameterClass="java.util.Map">
        select mytable.ID_COLUMN_IN_DATABASE_TABLE, mytable.NAME_COLUMN_IN_DATABASE_TABLE
        from mytable
        where mytable.name = #inputNames#
    </statement>
   
</sqlMap>

No comments: