简易基本MyBatis语句书写模板-续更中

1.trim标签替换where标签(查询操作)

<select id="queryBlogIf" parameterType="map" resultType="blog">
	select * from blog
		<trim prefix="WHERE" prefixOverrides="AND |OR ">
		<if test="title!= null and title!= """>
			title = #{title}
		</if>
		<if test="author != null and author != """>
			and author = #{author}
		</if>
	</trim>
</select>

2.trim标签助力insert标签(插入操作)

 <insert id="add"parameterType="cloud.xlh.my_system.pojo.Database">
 		INSERT INTO t_database
	 <trim prefix="(" suffix=")" suffixOverrides=",">
	 	<if test="dbName != null and dbName != """>
	 		db_name,
	 	</if>
	 	<if test="createTime != null">
	 		create_time 
	 	</if>
	 </trim>
	 <trim prefix="values(" suffix=")" suffixOverrides=",">
	 	<if test="dbName != null and dbName != """>
	 		#{dbName,jdbcType=VARCHAR},
	 	</if>
	 	<if test="createTime != null">
	 		#{createTime,jdbcType=Date}
	 	</if>
	 </trim>
</insert>

3.trim标签助力set标签(更新操作)

 <update
 id="update" parameterType="cloud.xlh.my_system.pojo.Database">
 		UPDATE t_database
	 <trim prefix="SET"  suffixOverrides=",">
	 	<if test="dbName != null and dbName != """>
	 		db_name = #{dbName,jdbcType=VARCHAR},
	 	</if>
	 	<if test="createTime != null">
	 		create_time = #{createTime,jdbcType=Date}
	 	</if>
	 </trim>
</update>

4.Choose语句

有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose
标签可以解决此类问题,类似于 Java 的 switch 语句
注意:适用于入参中只能一个有值的场景

<select id="queryBlogChoose" parameterType="map" resultType="blog">
	select * from blog
	<where>
		<choose>
			<when test="title != null">
				title = #{title}
			</when>
			<when test="author != null">
				and author = #{author}
			</when>
			<otherwise>
				and views = #{views}
			</otherwise>
		</choose>
	</where>
</select>

5.Foreach语句

将数据库中前三个数据的id修改为1,2,3;
需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息

<select id="queryBlogForeach" parameterType="map" resultType="blog">
	select * from blog
	<where>
		<!--
		collection:指定输入对象中的集合属性
		item:每次遍历生成的对象
		open:开始遍历时的拼接字符串
		close:结束时拼接的字符串
		separator:遍历对象之间需要拼接的字符串
		select * from blog where 1=1 and (id=1 or id=2 or id=3)
		-->
		<foreach collection="ids" item="id" open="and (" close=")"
		separator="or">
			id=#{id}
		</foreach>
	</where>
</select>

6.Bind元素

bind 元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。比如:

<select id="selectBlogsLike" resultType="Blog">
  <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{pattern}
</select>

原理参考:
NO.1
NO.2

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Fire king

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

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

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

打赏作者

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

抵扣说明:

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

余额充值