> 文档中心 > Mybatis使用动态SQL操作数据库

Mybatis使用动态SQL操作数据库


Mybatis动态SQL


文章目录

  • Mybatis动态SQL
  • 前言
  • 一、动态查询语句
    • 1:if判断
    • 2:where条件
    • 3:choose when otherwise
  • 二、新增
  • 三.修改
  • 四.删除
  • 小结

前言

动态SQL与传统SQL最大的特点就是传值的多样化,可使重复的SQL揉合成一条SQL语句


一、动态查询语句

1:if判断

if就是简单地条件判断,利用if语句可以使用某些简单地条件选择,所有的条件必须满足一个,也可以同时满足.

<select id="getStuByIf" parameterType="com.xh.bean.Student" resultType="com.xh.bean.Student">select * from student where 1=1<if test="id!=0">and id=#{id}</if><if test="sname!=null and sname!=''">and sname=#{sname}</if></select>

2:where条件

将if写进where里

<select id="getStuBywhere" parameterType="com.xh.bean.Student" resultType="com.xh.bean.Student">select * from student<where><if test="id!=0">and id=#{id}</if><if test="sname!=null and sname!=''">and sname=#{sname}</if></where></select>

3:choose when otherwise

choose when otherwise 一般是同时使用,当when中的条件不满足的时候,会执行otherwise里面的条件.

<select id="getStuBy" parameterType="com.xh.bean.Student" resultType="com.xh.bean.Student">select * from student <where><choose><when test="sname!=null and sname!=''">sname=#{sname}</when><otherwise>id=#{id}</otherwise></choose></where></select>

二、新增

trim:一般都用在新增上,其他位置也可以,不过没有新增最实用

<insert id="addStu" parameterType="com.xh.bean.Student">   insert into student   <trim prefix="(" suffix=")" suffixOverrides=",">      <if test="id!=0">  id,      </if>      <if test="sname!=null and sname!=''">  sname,      </if>   </trim>   <trim prefix="values(" suffix=")" suffixOverrides=",">      <if test="id!=0">  #{id},      </if>      <if test="sname!=null and sname!=''">  #{sname},      </if>   </trim></insert>

prefix:前缀覆盖并添加新的内容
suffix:后缀覆盖并添加新的内容
suffixOcerrides:后缀的判断条件

三.修改

关键词:set

<update id="updStu" parameterType="com.xh.bean.Student">   update student   <set>      <if test="sname!=null and sname!=''">  sname=#{sname},      </if>   </set>   <where>      id=#{id}   </where></update>

四.删除

foreach:循环关键词
collection:传入的集合
item:自己定义的名字
separator:or:循环删除

<delete id="deletes" parameterType="map">delete from student<where><foreach collection="lids" item="list" separator="or">id=#{list}</foreach></where></delete>

小结

本文讲述了Mybatis中动态SQL语句,虽然比传统SQL语句多一点,但是遇到一些大的项目,或者需求量高的项目,你使用动态SQL可以事半功倍,如鱼得水,基本都是关键字,只要稍微敲几遍应该就能铭记于心了.
有哪里不足或者有更好的建议,欢迎留言吐槽,如果有哪里不懂得可以私信博主,博主将一一回复,感谢认可,感谢支持!