mybatis动态SQL之 —— 武功秘籍(一)

mybatis秘籍之—— 标签

在这里插入图片描述

mybtis秘籍之 —— (CRUD) SQL语句

insert

  1. id :唯一的标识符
  2. parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User
<insert id="insert" parameterType="Object">
    insert into student (student_id,stydent_name) values (#{studentId},#{stydentName})
</insert>

delete

  1. id :唯一的标识符
  2. parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User
<delete id="deleteById" parameterType="Object">
    delete from student where id=#{id}
</delete>

update

  1. id :唯一的标识符
  2. parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User
<update id="alter" >
      	  UPDATE student SET student_name= #{studentName} where  student_id= #{studentId}
</update>

select

  1. id :唯一的标识符
  2. parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User 或 user
  3. resultType:语句返回值类型或别名。注意,如果是集合,那么这里填写的是集合的泛型,而不是集合本身(resultType 与 resultMap不能并用)
<select id="findStudentById" resultMap="BaseResultMap" parameterType="Object">
    select * from student where id=#{id}
</select>

mybatis秘籍之——动态SQL拼接

if 语句

if 标签通常用于 WHERE 后面,通过判断参数值来决定是否使用某个条件、插入某个字段的值。

<select id="findStudentById" resultMap="BaseResultMap" parameterType="Object">
    select * from student where 1=1
    <if test="studentId != null and studentId != ''">
    	and student_id =#{studentId }
    </if>
    <if test="studentName!= null and studentName!= ''">
    	and student_name =#{studentName}
    </if>
</select>

foreach语句

foreach 标签主要用于构建 in 条件,可在 sql 中对集合进行迭代。也常用到批量删除、添加等操作中。

属性:

  1. collection:collection 属性的值有三个分别是 list、array、map 三种,分别对应的参数类型为:List、数组、map 集合。
  2. item :表示在迭代过程中每一个元素的别名
  3. index :表示在迭代过程中每次迭代到的位置(下标)
  4. open :前缀
  5. close :后缀
  6. separator :分隔符,表示迭代时每个元素之间以什么分隔
<!-- in查询所有,不分页 -->
<select id="selectIn" resultMap="BaseResultMap">
    select name,hobby from student where id in
    <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
        #{item}
    </foreach>
</select>

choose语句

choose类似于 Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

按顺序判断 when 中的条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when的条件都不满则时,则执行 otherwise 中的 sql。

if 是与(and)的关系,而 choose 是或(or)的关系。

<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap">
    SELECT * from STUDENT WHERE 1=1
    <where>
        <choose>
            <when test="Name!=null and student!='' ">
                AND name LIKE CONCAT(CONCAT('%', #{student}),'%')
            </when>
            <when test="hobby!= null and hobby!= '' ">
                AND hobby = #{hobby}
            </when>
            <otherwise>
                AND AGE = 15
            </otherwise>
        </choose>
    </where>
</select>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值