这里提到的动态SQL用法都是基于mapper的xml配置文件的。
1、if 这个标签可以用于多条件查询,也可以用于新增/更新数据时的空值判断。
<select id="selectUser" resultType="com.forest.owl.entity.User">
select * from user
where 1=1
<if test="userName != null and userName != '' ">
and user_name like concat('%', #{userName}, '%')
</if>
<if test="userPhone != null and userPhone !='' ">
and user_phone=#{userPhone}
</if>
</select>
2、choose,用于模式匹配
<select id="selectUser" resultType="com.forest.owl.entity.User">
select * from user
where 1=1 /*此处不可忽略*/
<choose>
<when test="id != null">
and id=#{id}
</when>
<when test="userName != null and userName !='' ">
and user_name=#{userName}
</when>
<otherwise>
and 1=2 /*此处不可忽略*/
</otherwise>
</choose>
</select>
3、where,结合if使用
where标签内如果没有符合条件的选项,则最后生成的sql语句不含where;如果有符合条件的,则生成的sql语句会自动去除两端的and
<select id="selectUser" resultType="com.forest.owl.entity.User">
select * from user
<where>
<if test="userName != null and userName != '' ">
and user_name like concat('%', #{userName}, '%')
</if>
<if test="userEmail != null and userEmail != '' ">
and user_email = #{userEmail}
</if>
</where>
</select>
4、set,结合if使用
<update id="updateUserById">
update user
<set>
<if test="userName != null and userName != '' ">
user_name=#{userName},
</if>
id=#{id} /*此处不可忽略*/
</set>
where id=#{id}
</update>
5、foreach
collection:必填,值为要迭代循环的属性名。
item:变量名,值为要从迭代对象中取出的每一个值
index:索引的属性名。在集合数组下为索引值,在Map对象下为Map的key值。
参数为List的情况
<select id="selectByIdList" resultType="com.forest.owl.entity.User">
select * from user
where id in
<foreach collection="list" open="(" close=")" separator="," item="id" index="i">
#{id}
</foreach>
</select>
参数为Map的情况
<update id="updateByMap">
update user
set
<foreach collection="_parameter" item="val" index="key" separator=",">
${key}=#{val}
</foreach>
where id=#{id}
</update>
6、bind
bind标签可以使用OGML表达式创建一个变量并绑定到上下文中。如:
<if test="userName != null and userName != '' ">
and user_name like concat('%', #{userName}, '%')
</if>
可以通过bind改写成
<if test="userName != null and userName != '' ">
<bind name="userNameLike" value=" '%' + userName + '%' "/>
and user_name #{userNameLike}
</if>
7、如果测试的时候想知道映射XML中方法执行的参数 可以这么做:
public class StringUtil{
public static void print(Object parameter){
System.out.println(parameter);
}
}
<bind name="print" value="@com.forest.owl.util.StringUtil@print(_parameter)" />
8、鉴别器映射(discriminator) 有时单独一个映射会需要返回不同数据类型的结果集,discriminator就是为了用来处理这种情况。
因为感觉这个标签不会很常用,所以不做进一步了解,暂时给出简单的代码,后续有需要再回来翻阅:
<resultMap id="UserAndRole" extends="BaseResultMap" type="com.forest.owl.entity.User">
<discriminator javaType="int" column="enabled">
<case value="1" resultMap="resultMap1"/>
<case value="2" resultMap="resultMap2"/>
</discriminator>
</resultMap>
9、既然提到了动态sql,就额外提一下在注解形式下怎么写mapper吧。因为当前做的项目用到了这种方式,就在此mark一下。 举个多条件查询的小例子):
@Select("<script>
select id, name
from user
<where>
<if test='user.id != null'>id = #{user.id}</if>
<if test='user.name != null'>name like concat('%',#{user.name},'%')</if>
</where>
</script>")
User selectUser(@Param("user") User user);