动态Sql语句
动态sql语句的作用是本质还是实现字符串的拼接的。但是他可以解决各种问题
首先
select * from book where
<if test="bookname != null and bookname != ''">
bookname = #{bookname}</if>
<if test="bookname != null and bookname != ''">
and bookname = #{bookname}</if>
<if test="bookname != null and bookname != ''">
and bookname = #{bookname}</if>
注意你上面应该是三个不一样的字段名称,我这里为了好写就写成一样的了。
咱们来分析一下这种写法能干什么,可以实现多条件查询,
缺点:当你后面的条件如果全为空的时候呢,语句会变成什么样子。当你后面第一条语句为空后面的不为空时又会变成什么样子。
前者:
select * from book where
后者:
select * from book where and ?
可以看出这样的sql语句并不正确,那怎么办
1.我们可以在where后面添加一个恒等式
像这样:
select * from book where 1=1
<if test="bookname != null and bookname != ''">
bookname = #{bookname}</if>
<if test="bookname != null and bookname != ''">
and bookname = #{bookname}</if>
<if test="bookname != null and bookname != ''">
and bookname = #{bookname}</if>
这样就解决了上面出现的两个问题
2.使用where 或者trim标签
where标签他可以自动生成where关键字,也可以去除多余关键字,像上面的and这种,如果where内没有内容,那么这个标签就没什么作用
<select id="" >
select * from book
<where>
<if test="bookname != null and bookname != ''">
bookname = #{bookname}</if>
<if test="bookname != null and bookname != ''">
and bookname = #{bookname}</if>
<if test="bookname != null and bookname != ''">
and bookname = #{bookname}</if>
</where>
</select>
注意如果你的and 在后面那where是不能去除他的。
<where>
<if test="bookname != null and bookname != ''">
bookname = #{bookname} and
</if>
<if test="bookname != null and bookname != ''">
bookname = #{bookname}</if>
trim标签他和where没啥大的区别,就是比where更智能更先进。
他里面有四个属性:
prefix|suffix,prefixOverrides|suffixOverrides
第一组是添加,第二组是去掉
<select id="" >
select * from book
<trim prefix="where" suffixOverrides="and|or">
<!--注意这里suffixOverrides他想要去掉多个属性,你可以使用|-->
<if test="bookname != null and bookname != ''">
bookname = #{bookname}</if>
<if test="bookname != null and bookname != ''">
and bookname = #{bookname}</if>
<if test="bookname != null and bookname != ''">
and bookname = #{bookname}</if>
</trim>
</select>
若标签中没有内容那trim也没什么作用。
4.choose,when,otherwise
when相当于if,else if
otherwise表示其他情况相当于else
<select id="" >
select * from book
<where>
<choose>
<when test=""></when>
<when test=""></when>
<otherwise>
</otherwise>
<!--注意这里when至少有一个otherwise最多一个,(里面的条件自己写)-->
</choose>
</where>
</select>
5.foreach标签
实现批量操作
<delete id="">
delete from book where bookid in
<foreach collection="bookids" item="bookid" separator=","open="(",close=")" >
#{eid}
</foreach>
</delete>
批量添加
<insert id="">
insert into book values
<foreach collection="books" item = "book" separator=",">
(null,#{book.bookname},#{book.type},#{book.price})
</foreach>
</insert>
这里面的books是你要批量添加的数组或者集合,book是集合中的项,separator是分隔符,open是开始符,close是结束符。
for(Book book:books){…}意思和这个差不多
6.sql标签
sql标签里放sql片段,常用sql拿出来在标签里记录,直接在sql语句中用<include></include>
使用
<sql id="example">bookid,bookname,type,price</sql>
<select id="接口方法名">
select <include refid="example"></include> from book
</select>