标签:当多种类型的查询语句的查询字段或者查询条件相同时,可以将其定义为常量,方便调用。
<sql id="allColumns">
id,username,birthday,sex,address
sql>
标签:用于引用定义的常量。
<select id="getAll" resultType="users" >
select <include refid="allColumns">include>
from users
select>
标签:进行条件判断,配合其他标签使用。
<if test="userName != null and userName != '' ">
and username like concat('%',#{userName},'%')
if>
标签:where标签的作用:让where子句更加动态智能。
有多个if查询条件时,进行多条件拼接。
<select id="getByCondition" resultType="users" parameterType="users">
select <include refid="allColumns">include>
from users
<where>
<if test="userName != null and userName != '' ">
and username like concat('%',#{userName},'%')
if>
<if test="birthday != null ">
and birthday = #{birthday}
if>
<if test="sex != null and sex !=''">
and sex = #{sex}
if>
<if test="address != null and address !=''">
and address like concat('%',#{address},'%')
if>
where>
select>
标签:使用 if+set 标签,在进行表单更新的操作中,哪个字段中有值才去更新,如果某项为 null 则不进行更新,而是保持数据库原值。
至少更新一列,不更新别调这个更新方法,会报错。
<update id="updateBySet" parameterType="users">
update users
<set>
<if test="userName != null and userName != ''">
username = #{userName},
if>
<if test="birthday != null">
birthday = #{birthday},
if>
<if test="sex != null and sex != ''">
sex =#{sex},
if>
<if test="address != null and address !=''">
address = #{address}
if>
set>
where id = #{id}
update>
标签:<choose>
<when>when>
<when>when>
<when>when>
<otherwise>otherwise>
choose>
等同于:
if(){
}else if(){
}else if(){
}else if(){
}else{
}
标签:主要用来进行集合或数组的遍历,动态生成SQL,主要有以下参数:
collection:collection 属性的值有三个分别是 list、array、map 三种,分别对应的参数类型为:List、数组、map 集合。
item :循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details,在list和数组中是其中的对象,在map中是value。
index :在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
open :表示该语句以什么开始。
close :表示该语句以什么结束。
separator :表示元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
批量查询:
<select id="getByIds" resultType="users">
select <include refid="allColumns">include>
from users
where id in
<foreach collection="array" item="id" separator="," open="(" close=")">
#{id}
foreach>
select>
<delete id="deleteBatch" >
delete from users where id in
<foreach collection="array" item="id" close=")" open="(" separator=",">
#{id}
foreach>
delete>
<insert id="insertBatch" >
insert into users(username,birthday,sex,address) values
<foreach collection="list" separator="," item="u">
(#{u.userName},#{u.birthday},#{u.sex},#{u.address})
foreach>
insert>
<update id="updateSet" >
<foreach collection="list" item="u" separator=";">
update users
<set>
<if test="u.userName != null and u.userName != ''">
username=#{u.userName},
if>
<if test="u.birthday != null">
birthday = #{u.birthday},
if>
<if test="u.sex != null and u.sex != ''">
sex = #{u.sex},
if>
<if test="u.address != null and u.address != ''">
address = #{u.address}
if>
set>
where id = #{u.id}
foreach>
update>
注意:要使用批量更新,必须在jdbc.properties属性文件中的url中添加&allowMultiQueries=true,允许多行操作。