MyBatis之<if><where><foreach>查询

今天做项目的时候想起来了mybatis中查询后面还可以跟where if等等 做个小总结!!! 表的话我们就用 deptinfo表

1.定义全局sql语句 以后用来重复使用
<!--定义SQL语句-->
<sql id="selectAll">
	select dname from deptinfo
</sql>
2.定义select查询
<!-- id:DAO层中查询的方法名称,    resultType:这个查询返回的类型     -->     
    <select id="query1" resultType="com.entity.DeptInfo">
        <!--引用上面我们定义的全局sql 来使用-->
        <include refid="selectAll"></include>
        <!--如果where标签有语句输出,自动在语句前加上where关键字,并且去除第一个and/or关键字-->
        <where>
	          <if test="dname!=null">
	               and dname like concat("%",#{dname},"%")
	           </if>
        </where>
    </select>
3.foreach属性

foreach 用于迭代传入过来的参数

  • collection:表示传入过来的参数的数据类型。该参数为必选。要做 foreach 的对象,作为入参时,List 对象默认用 list 代替作为键,数组对象有 array 代替作为键,Map 对象没有默认的键。当然在作为入参时可以使用 @Param(“keyName”) 来设置键,设置 keyName 后,list,array 将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:
    如果 User 有属性 List ids。入参是 User 对象,那么这个 collection = “ids” 如果 User 有属性 Ids ids;其中 Ids 是个对象,Ids 有个属性 List id;入参是 User 对象,那么 collection = “ids.id”

    • 如果传入的是单参数且参数类型是一个 List 的时候,collection 属性值为 list
    • 如果传入的是单参数且参数类型是一个 array 数组的时候,collection 的属性值为 array
    • 如果传入的参数是多个的时候,我们就需要把它们封装成一个 Map 了,当然单参数也可以封装成 map。
  • item: 循环体中的具体对象。支持属性的点路径访问,如 item.age,item.info.details。具体说明:在 list 和数组中是其中的对象,在 map 中是 value,该参数为必选。(它是每一个元素进行迭代时的别名)

  • 在 list 和数组中,index 是元素的序号;在 map 中,index 是元素的 key。

  • open:表示该语句以什么开始

  • close:表示该语句以什么结束

  • separator:表示在每次进行迭代之间以什么符号作为分隔符

  1. 如果我们传的是一个 long[]的数组, 那我们就把 collection 设置为参数名
插入
<insert id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username, password, email, bio) values
  <foreach item="item" collection="list" separator=",">
    (#{item.username}, #{item.password}, #{item.email}, #{item.bio})
  </foreach>
</insert>
删除
delete id="one">
        delete from Author where id in
        <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </delete>
查询
<select id="one">
        select *from Author  where id in
        <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

array 是你dao层的 @Param变量指定的值
item 是你循环这个list里面 给一个变量去赋值

这里小编只是记录一下,建议大家学习一门新的框架的时候,先去看官网资料,尽量去看英文的,英文不好的小伙伴可以选择中文!!!

MyBatis官方

转载:https://blog.csdn.net/czd3355/article/details/75340080

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

往日时光--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值