动态sql语句中,主要掌握if、where、set、foreach、bind,其余的标签了解即可。
一、if
<select id="selectMore" resultType="flower">
SELECT * from flower where 1=1
<!--OGNL表达式-->
<if test="param1!=null and param1!=''">
and name=#{param1}
</if>
<if test="param2!=null and param2!=''">
and production=#{param2}
</if>
</select>
注意:在if的test里面直接写param1就行,不用写成#{param1},#{param1}是用在sql语句中充当占位符的。
二、where
<!--Where标签的作用:会自动的增加where关键字,并且会把多余的第一个and去掉-->
<select id="selectMore2" resultType="flower">
SELECT * from flower
<!--OGNL表达式-->
<where>
<if test="param1!=null and param1!=''">
name=#{param1}
</if>
<if test="param2!=null and param2!=''">
and production=#{param2}
</if>
</where>
</select>
三、set
<!--Set 会自动增加set关键字,并且去除最后一个逗号-->
<update id="update">
UPDATE flower
<set>
<if test="name!=null and name!=''">
name=#{name},
</if>
<if test="production!=null and production!=''">
production=#{production},
</if>
</set>
where id=#{id}
</update>
四、when
类似于if(){...
}else if(){
......}else{
......
}
<select id="selectMore4" resultType="flower">
SELECT * from flower
<where>
<choose>
<when test="param1!=null and param1!=''">
name=#{param1}
</when>
<when test="param2!=null and param2!=''">
and production=#{param2}
</when>
<otherwise>
1=1
</otherwise>
</choose>
</where>
</select>
五、trim
<!--
trim:
prefix:添加前缀
prefixOverrides:去除前缀
suffix:添加后缀
suffixOverrides:去除后缀
-->
<update id="update2">
UPDATE flower
<trim prefix="set" suffixOverrides=",">
<if test="name!=null and name!=''">
name=#{name},
</if>
<if test="production!=null and production!=''">
production=#{production}
</if>
</trim>
where id=#{id}
</update>
六、foreach
foreach标签是用来遍历集合的,在传参中,参数类型为list或者array的就不能再通过param的方式获得值了,应该通过list或array。
<select id="selectList" resultType="flower">
select * from flower
<where>
<if test="list!=null">
id in
<foreach collection="list" open="(" separator="," close=")" item="item">
#{item}
</foreach>
</if>
</where>
</select>
接口方法:
List<Flower> selectList(List<Integer> col);
七、bind
bind是用来模糊查询的,用${}这种方式也可以但是不安全,所以一般使用bind来进行模糊查询
<select id="selectBind" resultType="flower">
select <include refid="sql1"/>,production from flower
<where>
<if test="param1!=null and param1!=''">
<bind name="pa" value=" '%'+param1+'%' "/>
name like #{pa}
</if>
</where>
</select>
接口方法:
List<Flower> selectBind(String name);
八、include和sql
它们是用来提取和注入公共代码块的,比如经常用sql来提取常用的属性字段
<sql id="sql1">
id,name,price
</sql>
<select id="selectBind" resultType="flower">
select <include refid="sql1"/> from flower
<where>
<if test="param1!=null and param1!=''">
<bind name="pa" value=" '%'+param1+'%' "/>
name like #{pa}
</if>
</where>
</select>