1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > mybatis <where> <choose>标签

mybatis <where> <choose>标签

时间:2019-05-04 15:55:48

相关推荐

mybatis <where> <choose>标签

当遇到多个查询条件,使用where 1=1 可以很方便的解决我们的问题,但是这样很可能会造成非常大的性能损失,因为添加了 “where 1=1 ”的过滤条件之后,数据库系统就无法使用索引等查询优化策略,数据库系统将会被迫对每行数据进行扫描(即全表扫描) 来比较此行是否满足过滤条件,当表中的数据量较大时查询速度会非常慢;此外,还会存在SQL 注入的风险。

where标签方式

<select id="findActiveBlogLike" resultType="Blog">SELECT * FROM BLOG<where>is_delete=0<if test="state != null">state = #{state}</if><if test="title != null">AND title like #{title}</if><if test="author != null and author.name != null">AND author_name like #{author.name}</if></where></select>

choose (when, otherwise)标签

有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

<choose><when test="isUpdate !=null ">AND u.is_update = #{isUpdate, jdbcType=INTEGER}</when><when test="isDelete != null">AND u.is_delete = #{isDelete, jdbcType=INTEGER}</when><otherwise></otherwise></choose>

foreach标签

动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:

<select id="selectPostIn" resultType="domain.blog.Post">SELECT *FROM POST PWHERE ID IN<foreach item="item" index="index" collection="list"open="(" separator="," close=")">#{item}</foreach></select>

include标签

<mapper namespace="com.test.BaseDAO"><sql id="where">STATUS IN (1,2,3,4)</sql></mapper><select id="findAll" resultMap="BaseResultMap">SELECT * FROM TEST WHERE <include refid="com.test.BaseDAO.where"/></select>

trim标签

select * from user_tab where last_name=#{lastName} and age=#{age} and phone=#{phone}

使用示例

<select id="getUser" resultType="user">select * from user_tab <trim prefix="where">last_name=#{lastName} and age=#{age} and phone=#{phone}</trim></select>

prefixOverrides 使用

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

在动态sql的查询过程中,如果 lastName为null,所以第一个if不成立,里面的SQL语句不拼接,第二个if里面的and边紧跟在where后面了,语法错误。为了解决这个问题,只要加上prefixOverride即可,表示把动态生成的sql中,trim标签内的首个“and”去掉。

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

suffixOverrides的使用

update user_tab set ast_name=?, age=?,

若phone的值为null,则会导致生成的sql语句最后一个符号为“,”,导致生成的sql出错。为了避免此种情况,可使用trim标签中的suffixOverrides 将最后面的一个符号覆盖掉。

<update id="updateUser"><trim suffix="where id=#{id}" suffixOverrides=",">update user_tabset<if test="lastName != null">last_name=#{lastName},</if><if test="age != null">age=#{age},</if><if test="phone != null">phone=#{phone}</if> </trim></update>

resultType

resultType="java.lang.Integer"

<select id = "selectMaxAgeBySex" resultType="java.lang.Integer">select max(age) from user where sex = '女'</select>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。