第一种:
使用mysql的拼接函数,concat(),好处是使用#{}占位符可以防止sql注入,不好的地方是,如果换其他数据库的话,需要修改
<select id="list" parameterType="com.pkbin.blog_v2.blog.entity.MessageEntity" resultMap="messageMap">
select * from message
<where>
<if test="user!=null and user!=''">
and user like concat('%', #{user}, '%')
</if>
<if test="status!=null and status!=-1">
and status=#{status}
</if>
</where>
</select>
第二种:
使用${}拼接符,好处是是直接拼接,所有数据库都可以通用,坏处是可能会有sql注入
<select id="list" parameterType="com.pkbin.blog_v2.blog.entity.MessageEntity" resultMap="messageMap">
select * from message
<where>
<if test="user!=null and user!=''">
and user like '%${user}%'
</if>
<if test="status!=null and status!=-1">
and status=#{status}
</if>
</where>
</select>
第三种:
使用bind标签,动态拼接sql,可以达到所有数据库通用,并且防止sql注入的情况
<select id="list" parameterType="com.pkbin.blog_v2.blog.entity.MessageEntity" resultMap="messageMap">
select * from message
<where>
<if test="user!=null and user!=''">
<bind name="like_user" value="'%' + user + '%'"/>
and user like #{like_user}
</if>
<if test="status!=null and status!=-1">
and status=#{status}
</if>
</where>
</select>
总的来说,如果确定使用mysql数据库,推荐第一种方法,如果有可能更换数据库推荐使用第三种方法,第二种方法不推荐使用。