1、MyBatis prefixOverrides 作用

在实际项目开发中,经常需要根据不同条件拼接SQL语句,拼接时还要确保不能忘了必要的空格,有时候还要注意省掉列名列表最后的逗号...等等。在使用JDBC 或其他类似持久层框架操作数据库时,处理这种情况是非常麻烦的,甚至可以用痛苦来形容,而在MyBatis中利用 prefixOverrides 特性可以很简单地解决这个问题。

2、prefixOverrides 使用场景介绍

<select id="getUser" resultType="user">
 select * from t_users 
 <trim prefix="where">
  <if test="name != null">
   name=#{name}
  </if>
  <if test="age != null">
   and age=#{age}
  </if>
  <if test="phone != null">
   and phone=#{phone}
  </if>
 </trim>
</select>

在动态 SQL 的拼接过程中,如果 name 为 null,则第一个 if 不成立,里面的 SQL 语句不拼接,第二个 if 里面的 and 会紧跟在 where 后面,造成语法错误,最终动态生成的 SQL 如下:

select * from t_users where and age = ? and phone = ?

为了解决这个问题,只要加上 prefixOverrides 即可:

<select id="getUser" resultType="user">
 select * from t_users 
 <trim prefix="where" prefixOverrides="and">
  <if test="name != null">
   name=#{name}
  </if>
  <if test="age != null">
   and age=#{age}
  </if>
  <if test="phone != null">
   and phone=#{phone}
  </if>
 </trim>
</select>

3、提醒

prefix 是给整个字符串增加一个前缀,而 prefixOverrides 则是去掉整个字符串前面多余的字符。

4、参考

http://www.mybatis.cn/mybatis/53.html

标签: none

[网站公告]-[2024年兼职介绍]


添加新评论