mybatics 查询数据问题
不想看可以跳到最后解决方法去除foreach添加空格问题
通过条件查询数据,有时必须使用模糊查询。大多数情况下使用如下代码进行拼接
例:
<if test="searchCond.contents != null">
AND n.contents LIKE '%${searchCond.contents}%'
</if>
但是 当需要多次拼接查询的时候拼接起来会很复杂
例:
<if test="searchCond.assignUserVal != null and searchCond.assignUserVal.size > 0">
AND (
<foreach collection='searchCond.assignUserVal' item='item' index='index'>
<if test = "index != 0" >
OR
</if>
f_is_overlap(detail.act_user, '${item}')
</foreach>
)
</if>
而使用正则进行模糊查询比较方便
例(使用的是postgre数据库进行查询):
WHERE detail.act_user ~ 'test|notest'
上面代码我写到mybatics里运行却查不到任何内容
例:
<if test="searchCond.assignUserVal != null and searchCond.assignUserVal.size > 0">
AND detail.act_user ~
<foreach collection='searchCond.assignUserVal' item='item' index='index' open=''' separator='|' close='''>
${item}
</foreach>
</if>
经过找大佬的排查发现上面的例子mybatics拼接的时候会自动加上空格变成下面的样子
AND detail.act_user ~ ' test | test2 '
仔细看test前后会有空格所以导致查不到结果
解决方法1:
加上replace去除空格
例:
AND detail.act_user ~ replace (' test | test2 ', ' ', '') //弊端会把所有空格去掉
mybatics中代码
<if test="searchCond.assignUserVal != null and searchCond.assignUserVal.size > 0">
AND detail.act_user ~ replace (
<foreach collection='searchCond.assignUserVal' item='item' index='index' open=''' separator='|' close='''>
${item}
</foreach>
, ' ', '')
</if>
依然运行不出结果但是我把mybatics拼接的代码拿出来单独运行是有结果的
如果有大佬能帮我解决这个问题感激不尽
解决方法2:
直接上代码
<if test="searchCond.assignUserVal != null and searchCond.assignUserVal.size > 0">
AND detail.act_user ~
<foreach collection='searchCond.assignUserVal' item='item' index='index' open=''' separator='|' close='''>${item}</foreach>
</if>
很无语把 ${item}前后换行符去了就可以