一、resultMap与resultClass
iBatis常见的返回值参数类型有:resultMap与resultClass
这两种类型的选择可以用两句话说明:
1.当结果集列名和类的属性名完全对应时,可直接使用resultClass来直接指定查询结果类型。
这种很常用,例如,
<typeAlias alias="ibeacon" type="com.s2si.model.Ibeacon"/>
<select id="selectibeaconlist" resultClass="ibeacon" parameterClass="int">
<![CDATA[
select * from t_ibeacon where ibeaconid>#ibeaconid# and isavailable=1
]]>
</select>
2.当查询的结果集合属性名无法对应的时候,可以采用resultMap指定列名与对象属性名之间的对应关系,否则对应不上的属性将为null或者0.
这种也是本文想重点讲述的。
resultMap映射结果的目的就是要将查询的结果集绑定到映射对象的属性上。其实对于这种情况用resultClass也是可以解决的,即将查询结果列用as重命名。
PS,写到前面吧,com.ibatis.sqlmap.client.SqlMapClient.sqlMap.queryForMap(String arg0, Object arg1, String arg2)函数参数说明:
第一个statement,第二个插入入参,第三个返回的Map集合的key。
二、问题描述
一般如果需要用resultClass来作为结果集对应的话,那就必须首先声明对应的类,不过有的时候,我们仅仅需要取其中一个值而已,若再因此而去声明一个新类,不太值得。所以考虑使用resultMap。
问题:对传过来的签到数据(公司签到打卡,不是类似人人的每日签到),和规定的上下班时间进行比对,然后标示异常与否,然后存入数据库。
关键点:取得规定的上下班时间,存储在公司表中。比如上午9:00,下午17:30这样。
简单起见,我想直接取得上下午规定打卡小时和分钟,共计四个数据
结果形式如下:{2={amminute=20, pmminute=0, pmhour=17, amhour=9, eid=2}}
name | 值 | 说明 |
---|---|---|
amhour | 9 | 上午规定打卡时间,hour |
amminute | 0 | 上午,minute |
pmhour | 17 | 下午,hour |
pmminute | 30 | 下午,minute |
三、问题解决
3.1 Model.xml
<resultMap id="nameMap" class="java.util.HashMap">
<result property="eid" column="eid" javaType="java.lang.Integer"/>
<result property="amhour" column="amhour" javaType="java.lang.Integer"/>
<result property="amminute" column="amminute" javaType="java.lang.Integer"/>
<result property="pmhour" column="pmhour" javaType="java.lang.Integer"/>
<result property="pmminute" column="pmminute" javaType="java.lang.Integer"/>
</resultMap>
<select id="selectampmtime" resultMap="nameMap">
<![CDATA[
select emp.employeeid as eid,hour(amtime) as amhour,minute(amtime) as amminute,hour(pmtime) as pmhour,minute(pmtime) as pmminute from t_company as com,t_employee as emp where emp.employeeid=#employeeid# and emp.companyid=com.id
]]>
</select>
3.2 Impl类
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
Date cDate =new Date();// new Date()为获取当前系统时间
parms.put("signtime", df.format(cDate));
Calendar calendar = Calendar.getInstance();
calendar.setTime(cDate);
//获取规定的上下午打卡时间
Map<Integer, Map<String, Integer>> ampmMapMap = sqlMap.queryForMap("selectampmtime",String.valueOf(employee.getEmployeeid()),"eid");
Map<String, Integer> ampmMap =ampmMapMap.get(employee.getEmployeeid());
Integer amhour = ampmMap.get("amhour");
Integer amminute = ampmMap.get("amminute");
Integer pmhour = ampmMap.get("pmhour");
Integer pmminute = ampmMap.get("pmminute");
if ((calendar.get(Calendar.HOUR_OF_DAY)<amhour||(calendar.get(Calendar.HOUR_OF_DAY)==amhour&&calendar.get(Calendar.MINUTE)<=amminute))||(calendar.get(Calendar.HOUR_OF_DAY)>pmhour||(calendar.get(Calendar.HOUR_OF_DAY)==pmhour&&calendar.get(Calendar.MINUTE)>=pmminute))) {
parms.put("abnormal", 0);
}else {
parms.put("abnormal", 1);
}
四、总结
所以,基于iBatis进行增删改查等操作时,特别是查,并非必须声明一个类与之对应,而是采用resultMap也同样可以实现。