Mybatis基础学习笔记(五)-动态查询
Mybatis基础学习笔记(五)
动态sql
- 同一个sql在不同的条件下可以表示不同的sql语句
- 方法:使用Mybatis的标签,实现动态sql的能力:
- 主要包含的标签有:if、where、foreach、sql代码片段
- 使用动态sql时,方法的形参是java对象
if
-
<if test="id!=null ">
测试属性的值:OGNL -
<select id="findProductByPage" resultMap="productByPageMapper" parameterType="Condition"> select * from products <where> <if test="id!=null "> and id = #{id} </if> <if test="name!=null"> and name like #{name} </if> <if test="lp!=null"> and price >= #{lp} </if> <if test="hp!=null"> and price <= #{hp} </if> </where> limit ${(currentPage-1)*6} , ${6}; </select>
-
if标签在单独使用时存在where语句不能动态设置的问题,导致语法错误,在实际使用过程中常配合where标签使用
where
- 在使用where标签时,里面是一个或多个标签,当有一个if标签为真时,会自动拼接where,在不存在为真的if标签时,不会拼接where
foreach
- foreach可以在元素体内使用的集合项(item)和索引(index)变量
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="集合中的条目" index="索引" collection="集合类型"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
- 当集合中是引用类型时:
#{property.Xxx}
代码片段sql
-
灵活使用代码片段
-
<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql> <select id="selectUsers" resultType="map"> select <include refid="userColumns"><property name="alias" value="t1"/></include>, <include refid="userColumns"><property name="alias" value="t2"/></include> from some_table t1 cross join some_table t2 </select>