最近做了一些从hebernate到mybatis的迁移,hebernate中各种的关联查询原本想在mybatis中实现,可发觉没必要,只是多写几条sql的问题。关键是遇到map传递数组问题,折磨了不少时间,问题是这样的,sql中有一个查询,大概是where depId in ('1818','1058','999'),括号里面是数组,数组要从参数map取出,如何在xml文件中实现这条sql呢。
首先,map的类型要为map<String,Object>类型,这样值里面才能放入数组,我是这样写的:
Map<String,Object> map = new HashMap<String,Object>();
map.put("tag", "1818");
String childDeps="1000,1058,999";
String[] array = childDeps.split(",");
map.put("childdeps", array);
然后xml里面是这样的:
<select id="pagePoliciesByParamsMapWithDep" parameterClass="java.util.Map" resultClass="policyListItemBean">
select t.ID id,
t.NAME name,
t.DEVICE_TYPE deviceType,
t.TAG tag,
t.UPDATE_TIME updateTime,
t.IS_DEFAULT isDefault,
t.TYPE type,
pd.DEPID depId,
COUNT(d.ID) countOfDevicesInstalled
from (select * from (select * from t_c_policy t
where 1=1
<isNotNull prepend="AND" property="tag">
t.TAG =#tag#
</isNotNull>
<isNotEmpty prepend="AND" property="name">
t.NAME = #name#
</isNotEmpty>
)t
where NOT EXISTS(select * from policy_department pd where t.ID=pd.POLICYID)
or t.ID in (select POLICYID from policy_department b
where 1=1
<isNotNull prepend="AND" property="childdeps">
b.DEPID in
<iterate property="childdeps" open="(" close=")" conjunction=",">
#childdeps[]#
</iterate>
</isNotNull>
)
ORDER BY t.NAME)t LEFT JOIN policy_department pd ON t.ID=pd.POLICYID
LEFT JOIN t_c_binded_policy b ON t.ID=b.POLICY_ID
LEFT JOIN (SELECT * from t_c_device d where d.archieved='0'
and (d.status='2' or d.status='4')) d ON b.ID=d.ID GROUP BY t.ID ORDER BY t.NAME
</select>
这是一整条sql,关键部分是这里:
where 1=1
<isNotNull prepend="AND" property="childdeps">
b.DEPID in
<iterate property="childdeps" open="(" close=")" conjunction=",">
#childdeps[]#
</iterate>
</isNotNull>
有个细节要注意:键一定要全部小写,大写的话sql好像不认,我试过,如把childdeps写成childDeps,这个sql是不能执行的,即便能执行,这个数组也是读取不到的,这个错误我找了好久才找到这个地方。
存为备忘吧