在工作中离不开跟数据库打交道,目前流行的固然是mybatis,在xml中写sql的时候,可能会出现下面情况:
<select id="select" resultType="User">
select * from user2
where
<if test="name != null">
name = #{name}
if>
<if test="pwd != null">
and pwd = #{pwd}
if>
select>
上述写法问题,sql中可能会有where条件,但是条件的个数未定,且条件任意一条都随机成立:
1. 情况一:name与pwd 都不为空,sql正常
2. 情况二:name不为空,pwd为空,sql正常
3. 情况三:name为空,pwd不为空,sql异常,因为sql就变成select * from user2 where and pwd = #{pwd}
4. 情况四:name、pwd都为空,sql异常,因为sql就变成select * from user2 where
针对上述情况,有人可能会这样子解决,确实完全解决上述出现的问题,并且简单,但是唯一就是出现 1 = 1,很不美观:
<select id="select" resultType="User">
select * from user2
where 1 = 1
<if test="name != null">
and name = #{name}
if>
<if test="pwd != null">
and pwd = #{pwd}
if>
select>
为了追求更好的写法,因此则稍微研究了一下:mybatis中自带的标签完美解决这个事情,如下文。
mybatis中有标签,语法如下:
<trim prefix="" prefixOverrides="" suffix="" suffixOverrides="">trim>
prefix:若条件成立,在trim标签内sql语句前面加上前缀
prefixOverrides:若条件成立,在trim标签内原sql语句,原sql语句,前面去掉多余前缀内容
suffix:若条件成立,在trim标签内sql语句后面加上后缀
suffixOverrides:若条件成立,在trim标签内原sql语句,原sql语句,后面去掉多余后缀内容
例子:
<select id="select" resultType="User">
select * from user2
<trim prefix="where" prefixOverrides="ADN|and" suffix="" suffixOverrides="">
<if test="name != null and name.length() > 0">
and name = #{name}
if>
<if test="pwd != null and pwd.length() > 0">
and pwd = #{pwd}
if>
trim>
select>
最终XML的sql如下写:
<select id="select" resultType="User">
select * from user2
<trim prefix="where" prefixOverrides="ADN|and">
<if test="name != null">
and name = #{name}
if>
<if test="pwd != null">
and pwd = #{pwd}
if>
trim>
select>




