mybatis-动态sql

mybatis中的动态sql详解

什么是动态sql

动态sql是指sql并不事先确定好,而是在运行期动态生成。动态sql的出现,这不仅能令sql语句变得更加灵活,还能更近一步地优化sql语句的执行效率。

if

if的作用是当test中的条件满足时,将指定地sql语句添加入目标sql语句中。
下面是一个简单的示例。

<select id="queryBook" resultMap="BookResult">
	SELECT b.bid,b.btitle,a.apseudonym,p.pname
	FROM book_base_inf b
	LEFT JOIN author_base_inf a ON b.aid=a.aid
	LEFT JOIN publisher_base_inf p ON b.pid=p.pid
	WHERE 1=1
	<if test="title!= null">AND b.btitle LIKE #{title}</if>
	<if test="author!= null">AND a.apseudonym LIKE #{author}</if>
	<if test="publisher!= null">AND p.pname LIKE #{publisher}</if>
</select>

choose

chooes的作用与if的作用不同。chooes将第一个满足test中的条件的sql语句添加到目标sql语句中。
下面是一个简单的示例。

<select id="queryBook"
	resultMap="BookResult">
	SELECT b.bid,b.btitle,a.apseudonym,p.pname
	FROM book_base_inf b
	LEFT JOIN author_base_inf a ON b.aid=a.aid
	LEFT JOIN publisher_base_inf p ON b.pid=p.pid
	WHERE 1=1
	<choose>
		<when test="title!= null">AND b.btitle LIKE #{title}</when>
		<when test="author!= null">AND a.apseudonym LIKE #{author}</when>
		<when test="publisher!= null">AND p.pname LIKE #{publisher}</when>
		<otherwise>AND 1=2</otherwise>
	</choose>
</select>

trim

trim在java中的作用是去除首尾空白格。在mybatis中,trim有 了更加强大的功能。
下面是trim的使用模板。

<trim prefix="A" prefixOverrides="B">
  ...
</trim>

在这个示例中trim的作用是去除中间sql语句在首部的B,并且用A将其覆盖。
当A=“WHERE”,B="AND |OR "时,其等价于< where>

foreach

foreach的作用是迭代器。当传入的参数为集合时,foreach能迭代集合。
下面是一个简单的示例。

<select id="queryBook" resultMap="BookResult">
	SELECT b.bid,b.btitle,a.apseudonym,p.pname
	FROM book_base_inf b
	LEFT JOIN author_base_inf a ON b.aid=a.aid
	LEFT JOIN publisher_base_inf p ON b.pid=p.pid
	<trim prefix="WHERE " prefixOverrides="AND |OR ">
		<foreach item="book" index="index" collection="list">
			<if test="book.title!= null">AND b.btitle LIKE #{book.title}</if>
			<if test="book.author!= null">AND a.apseudonym LIKE #{book.author}</if>
			<if test="book.publisher!= null">AND p.pname LIKE #{book.publisher}</if>
		</foreach>
	</trim>
</select>

在上面的示例中,依次迭代类型为list的集合,并且将当前的元素赋值给变量book。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值