mybatis之动态SQL

1 动态SQL

mybatis中,它提供了一些动态sql标签,可以让程序员更快的进行mybatis的开发,这些动态sql可以通过sql的可重用性
常用的动态sql标签:if标签、where标签、sql片段、foreach标签

1.1 If/where

If标签/where标签:主要用于多功能组合查询
where标签可以去掉查询条件中的第一个and关键字

 <select id="getUsersByNameAndType" resultMap="userinfoResultMap" parameterType="hashmap">
	 	select 
	 		userId _userId,
	 		userName _userName,
	 		userPass _userPass, 
	 		userType _userType,
	 		address _address 
	 	from userinfo
	 	<!--where标签可以去掉查询条件中的第一个and关键字 -->
	 	<where>
	 		<if test="userName!=null and userName!=''">
	 			and userName like'%${userName}%'
	 		</if>
	 		<if test="userType!=0">
	 			and userType=#{userType}
	 		</if>
	 	</where>
	 </select>

1.2 Sql片段

Sql片段可以让代码有更高的可重用性,Sql片段需要先定义后使用

 <!-- SQL片段:Sql片段可以让代码有更高的可重用性,Sql片段需要先定义后使用-->
	 <sql id="nameAndTypeSQL">
	 		<if test="userName!=null and userName!=''">
	 			and userName like'%${userName}%'
	 		</if>
	 		<if test="userType!=0">
	 			and userType=#{userType}
	 		</if>
	 </sql>
	  <select id="getUsersBySQLNameAndType" resultMap="userinfoResultMap" parameterType="hashmap">
	 	select 
	 		userId _userId,
	 		userName _userName,
	 		userPass _userPass, 
	 		userType _userType,
	 		address _address 
	 	from userinfo
	 	<!--where标签可以去掉查询条件中的第一个and关键字 -->
	 	<where>
	 		<!-- 引入SQL片段 -->
	 		<include refid="nameAndTypeSQL"></include>
	 	</where>
	 </select>

1.3 foreach

foreach的官网文档

<select id= "selectPath" resultType="Post">
	select * from post where id in 
	<foreach item = "item" index = "index" collection = "list" open = "(" close = ")" separator = "," >
		#{item}
	</foreach>
</select>

1.3.1 foreach标签中的属性

属性描述
item循环体中的具体对象,每次迭代中获取的元素。支持属性的点路径访问,如item.ageitem.info.details。具体说明:在list和数组中是其中的对象,在map中是value。该参数为必选
collection要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象用map代替作为键。当然在作为入参时可以使用@Param(“keyName”)来设置键,设置keyName后,list,array,map将会失效,而是使用@Param指定的别名。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:如果User有属性List ids。入参是User对象,那么这个collection = "ids"如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"上面只是举例,具体collection等于什么,就看你想对那个元素做循环。该参数为必选
separator元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选
openforeach代码的开始符号,一般是(close=")"合用。常用在in(),values()时。该参数可选
closeforeach代码的关闭符号,一般是)open="("合用。常用在in(),values()时。该参数可选
indexlist数组中,index是元素的序号,在map中,index是元素的key,该参数可选

1.3.2 在xml中的使用

<insert id="insertBatch">
    insert into nef_qos_package (qos_reference, mar_bw_ul, mar_bw_dl,mir_bw_ul, mir_bw_dl, create_time,update_time)
    values
        <foreach collection="list" item="item" index="index" separator=",">
        (#{item.qosReference,jdbcType=VARCHAR}, #{item.marBwUl,jdbcType=VARCHAR}, #{item.marBwDl,jdbcType=VARCHAR},
        #{item.mirBwUl,jdbcType=VARCHAR}, #{item.mirBwDl,jdbcType=VARCHAR}, NOW(), NOW())
    </foreach>
    </insert>

1.3.3 foreach中index属性作用

在官方文档中当使用可迭代对象或者数组时,<foreach>标签中的index属性代表当前迭代次数

<insert id="batchInsertSelective" parameterType="list">
    insert into
      proc_pre_item (proc_tempt_id, type_id, sort, create_user, create_date)
    values
    <foreach collection="list" separator="," item="preItem" index="idx">
        (
            #{preItem.procTemptId,jdbcType=BIGINT},
            #{preItem.typeId,jdbcType=BIGINT},
            #{idx},
            #{preItem.createUser,jdbcType=BIGINT},
            #{preItem.createDate,jdbcType=TIMESTAMP}
        )
    </foreach>
</insert>

index就是 当前List集合遍历次数的计数器,故而使用它来 解决我们业务中 需要设置字段的值得变化。

在实际的项目中,需要对一个树节点进行上下移动操作,最后在提交数据后需要保存最后树节点的排序顺序。

实际在操作的时候,我们选择在业务代码的Service 层中进行数据的遍历,同时设置 节点的sort 值得变化,而且这样操作带来的一个最为直接的问题就是sort值得处理,如果是新增业务,还是容易解决的,但是,恰恰更多的是编辑操作,这样,在选择设置sort值得时候就要引进更多的 处理sort值的问题, 造成更为复杂的非业务逻辑功能。而且并不能保证数据的真确性。
使用 的index解决 排序值问题(sort字段可以每次重新生成)

因此在项目中使用 标签的index属性很好的解决了这个问题,最主要的是降低了代码的复杂度,提高可读性和功能的单一性以及可维护性。
有了这个神器, 我们就可以直接在service层处理业务相关的问题, 把sort值得设定交给 底层的sql在操作的时候自动处理,这样就保证了 sort值得唯一性。代码量大大的减少。
可能有人要问,那批量操作的时候夹杂着 更新和新增 节点的功能的时候,这个怎么处理,其实这个主要看你们项目的选择,对于树这种节点不是很多的操作可以使用这个方式,如果存在非常多的节点,建议直接使用Redis 的原子性操作解决
下面直接看最后我的 mybatis xml 中的代码 和最终数据库中数据:

<insert id="batchInsertSelective" parameterType="list">
<!--@mbggenerated -->
insert into
    proc_pre_item (proc_tempt_id, type_id, sort, create_user, create_date)
values
<foreach collection="list" separator="," item="preItem" index="idx">
    (
        #{preItem.procTemptId,jdbcType=BIGINT},
        #{preItem.typeId,jdbcType=BIGINT},
        #{idx},
        #{preItem.createUser,jdbcType=BIGINT},
        #{preItem.createDate,jdbcType=TIMESTAMP}
    )
</foreach>
</insert>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值