根据条件查询(name或者age条件可能只有一个存在),给出了两种写法:
用到了if和where标签
<!-- 根据条件查询,不用where标签
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user where 1=1
<if test="name != null">
and name = #{name}
</if>
<if test="age != null">
and age = #{age}
</if>
</select>-->
<!--使用where标签,#{}里面是传入的实体类的属性名,不能随意写-->
<select id="findUserByCondition" resultType="com.mbtest.domain.User" parameterType="com.mbtest.domain.User">
select * from userinfo
<where>
<if test="name != null">
and name = #{name}
</if>
<if test="age != null">
and age = #{age}
</if>
</where>
</select>
根据id集合(含有多个id)查询多行数据,用到了foreach标签:
属性: collection:id 集合,值为QueryVo类的属性名
open:开始 ,值为 "and id in ("
close:结束 , 值为 ")"
item:遍历的每一项,值为代号随便写,但下方#{}内的值要与之保持一致
separator:分隔号,逗号
<!-- 了解的内容:抽取重复的sql语句-->
<sql id="defaultUser">
select * from userinfo
</sql>
<!-- 根据queryvo中的Id集合实现查询用户列表 -->
<select id="findUserInIds" resultType="com.mbtest.domain.User" parameterType="com.mbtest.domain.QueryVo">
<include refid="defaultUser"></include>
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in (" close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
另外,当映射配置文件中存在某一sql语句的大量应用时,可以用sql标签把该语句抽取出来,并通过include标签对其进行使用