动态sql:根据不同的条件凭借不同的sql语句,实现对数据更精准的操作。
实现:映射器配置文件后者注解
常用动态sql元素:
select * from student
where 1=1
<if test="sid !=0">
and sid=#{sid}
</if>
<if test="sname !=null">
and sname=#{sname}
</if>
2.where标签:会自动地给Sql语句添加where关键字,并将第一个and去除。没有条件则不添加where,后面第一个条件时会自动去掉and/or,没有其他表达式的时候
select * from student
<where>
<if test="sid !=0">
and sid=#{sid}
</if>
<if test="sname !=null">
and sname=#{sname}
</if>
<if test="birthday !=null">
and birthday=#{birthday}
</if>
<if test="ssex !=null">
and ssex=#{ssex}
</if>
<if test="classid !=0">
and classid=#{classid}
</if>
</where>
3.choose when otherwise标签
特点:条件只要有一个成立,其他的就不会再判断了。如果没有成立的条件则默认执行otherwise中的内容,且查询顺序和在when中的标签顺序一样
select * from student where 1=1
<choose>
<when test="sid !=0">and sid=#{sid}</when>
<when test="sname !=null">and sname=#{sname}</when>
<when test="birthday !=null">and sname=#{sname}</when>
<when test="ssex !=null">and ssex=#{ssex}</when>
<when test="classid !=0">and classid=#{classid}</when>
<otherwise>and sid=21</otherwise>
</choose>
4.set标签:修改辅助
产生一个set关键字,自动去除最后一个逗号。
update student
<set>
<if test="sname !=null">sname=#{sname},</if>
<if test="birthday !=null">birthday=#{birthday},</if>
<if test="ssex !=null">ssex=#{ssex},</if>
<if test="classid !=0">classid=#{classid},</if>
</set>
<where>
sid=#{sid}
</where>
5.trim标签:
prefix:在trim的内容前添加指定的内容
prefixOverrides在trim的内容前去除指定的内容
suffix:在trim的内容后添加指定的内容
suffixOverrides:在trim的内容后去除指定的内容
update student
<trim prefix="set" suffixOverrides=",">
<if test="sname !=null">sname=#{sname},</if>
<if test="birthday !=null">birthday=#{birthday},</if>
<if test="ssex !=null">ssex=#{ssex},</if>
<if test="classid !=0">classid=#{classid},</if>
</trim>
<where>sid=#{sid}</where>
6.bind标签:一般用于模糊查询
name:参数名 value:表达式,注意字符串拼接按照变量方式进行拼接,
<bind name="sname" value="'%'+_parameter+'%'"/>
select * from student where sname like #{sname}
7.foreach标签:
item:集合中的元素 index:元素所在集合的下标,迭代map时,index是键
collection:集合的类型,可选值list,array,除此之外还可以是@Param("name")、Map中的key、类的成员变量 open、
close:在首、尾拼接的字符 separator:每个元素间的分隔符
传入单参数且是List时,collection="list"
传入单参数且是Array时,collection="array"
select * from student where
<foreach collection="array" item = "sid" open="sid in (" separator="," close=")">
#{sid}
</foreach>
注解的动态sql用法和sqlmapper的基本一样。下面用一个实例来形容
1.sql脚本
@Select("<script> select * from student"
+ " <where>"
+ "<if test=\"ssex !=null\"> and ssex=#{ssex} </if>"
+ "<if test=\"classid !=0\"> and classid=#{classid} </if>"
+ "</where>"
+ "</script>")
public List<Student> findAllStudent(Student s);
2.其他的动态 SQL 方法
@UpdateProvider(type =stuProvider.class ,method = "updateStudent")
public int upadteStudent(Student s);
class stuProvider {
public String updateStudent(Student s) {
String sql="update student set ";
if(s.getClass() !=null) {
sql +="classid =#{classid},";
}
if(s.getSname() !=null) {
sql +="sname =#{sname},";
}
if(s.getBirthday() !=null) {
sql +="birthday =#{birthday},";
}
if(s.getSsex() !=null) {
sql +="ssex =#{ssex},";
}
sql =sql.substring(0,sql.length()-1);
sql +="where sid=#{sid}";
return sql;
}