Search code examples
javaibatis

ArrayList Mapping in IBatis


How should I map multiple columns with List in IBATIS ?

I have a Bean, say :

public class AttendanceBean {
    private String user_id;
    private String user_name;
    private List daysArray;
    // setter/getter methods
}

Ibatis (select clause in sqlMap):

<select id="someName" parameter="param">
   select user_id,user_name,
        day_1,
        day_2,
        day_3,
         ...
         ...
        day_31
    from table1,table2 
    where table1.userid=table2.userid
<select>

My question is how I am going to Map AttendanceBean's daysArray with columns day_1, day_2, ... day_31 in ResultMap even though I can simply write JDBC code for this as follows:

List alluser = new ArrayList();
while (rs.next()) {
    AttendanceBean ab = new AttendanceBean();
    ab.setUser_id(rs.getString("USER_ID"));
    ab.setUser_name(rs.getString("USER_NAME"));
    List tempArray = new ArrayList(); 
    for (int i=1;i<=noOfDaysinMonth;i++) {
        tempArray.add(rs.getString("DAY_"+i));
    }
    ab.setDayArray(tempArray);
    alluser.add(ab);
}  

Solution

  • Faraz I take the daysArray is the number of days a particular user attended? It would be helpful to add some details of your schema. The table that has the number of days also has the user Id as well? Assuming you have a similar case you can do the following (this example is based on iBatis version 2.3.4).

    <select id="retrieveAllUserAttendences" resultMap="exampleUserAttendences">
        SELECT 
        table1.user_id, 
        table1.user_name,
        table2.day
        FROM table1
        INNER JOIN table2 ON table2.user_id = table1.user_id
    </select>
    
    <resultMap id="exampleUserAttendences" class="AttendanceBean" groupBy="user_id">
        <result property="user_id" column="user_id" jdbcType="VARCHAR" javaType="java.lang.String"/>        
        <result property="user_name" column="user_name" jdbcType="VARCHAR" javaType="java.lang.String"/> 
        <result property="daysArray" resultMap="sqlMapNamespace.exampleDaysResultMap" />       
    </resultMap>
    
    <resultMap id="exampleDaysResultMap" class="java.lang.String">
        <result property="daysArray" column="day_column_name" jdbcType="VARCHAR" javaType="java.lang.String"/>
    </resultMap>   
    

    Again I must stress this is an example and depends on how you store your data/schema is, however hope this example helps.