这里提到的动态SQL用法都是基于mapper的xml配置文件的。java
一、if 这个标签能够用于多条件查询,也能够用于新增/更新数据时的空值判断。sql
<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>
二、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>
三、where,结合if使用app
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>
四、set,结合if使用rest
<update id="updateUserById"> update user <set> <if test="userName != null and userName != '' "> user_name=#{userName}, </if> id=#{id} /*此处不可忽略*/ </set> where id=#{id} </update>
五、foreachcode
collection:必填,值为要迭代循环的属性名。xml
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>
六、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>
七、若是测试的时候想知道映射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)" />
八、鉴别器映射(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>
九、既然提到了动态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);