通过对姓名的模糊搜索,使用if判断姓名是否为空,如果为空,则是查询所有用户
<!-- 使用if元素根据条件动态查询用户信息-->
<select id="selectUserByIf" resultType="cn.test.beans.MyUser" parameterType="cn.test.beans.MyUser">
select * from user where 1 = 1
<if test="uname != null and uname != ''">
<!-- 这里是根据姓名模糊查找 -->
and uname like concat('%', #{uname}, '%')
</if>
<!-- concat()函数, 将多个字符串连接成一个字符串 -->
</select>
有的时候不想用到所有的条件语句,而只想从中择取一二,针对这种情况,MyBatis提供了<choose>元素,它有点像java中的switch语句。
<!-- 使用choose、when、otherwise元素根据条件动态查询用户信息-->
<select id="selectUserByChoose" resultType="cn.test.beans.MyUser" parameterType="cn.test.beans.MyUser">
select * from user where 1 = 1
<choose>
<when test="uname != null and uname != ''">
and uname like concat('%', #{uname}, '%')
</when>
<when test="usex != null and usex != ''">
and usex = #{usex}
</when>
<otherwise>
and uid > 10
</otherwise>
</choose>
</select>
<!-- 使用trim元素根据条件动态查询用户信息-->
<select id="selectUserByTrim" resultType="cn.test.beans.MyUser" parameterType="cn.test.beans.MyUser">
select * from user
<trim prefix="where" prefixOverrides="and | or">
<if test="uname != null and uname != ''">
and uname like concat('%', #{uname}, '%')
</if>
<if test="usex != null and usex != ''">
and usex = #{usex}
</if>
</trim>
</select>
<!-- 使用where元素根据条件动态查询用户信息-->
<select id="selectUserByWhere" resultType="cn.test.beans.MyUser" parameterType="cn.test.beans.MyUser">
select * from user
<where>
<if test="uname != null and uname != ''">
and uname like concat('%', #{uname}, '%')
</if>
<if test="usex != null and usex != ''">
and usex = #{usex}
</if>
</where>
</select>
运行结果和sql语句同上
<!-- 使用set元素动态修改一个用户-->
<update id="updateUserBySet" parameterType="cn.test.beans.MyUser">
update user
<set>
<if test="uname != null">
uname = #{uname}, <!--这里的逗号不能少-->
</if>
<if test="usex != null">
usex = #{usex}
</if>
</set>
where uid = #{uid}
</update>
<!-- 使用foreach元素查询用户信息-->
<select id="selectUserByForeach" resultType="cn.test.beans.MyUser" parameterType="List">
select * from user where uid in
<foreach collection="list" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</select>
// 使用foreach元素查询用户信息
List<Integer> listId = new ArrayList<Integer>();
listId.add(34);
listId.add(37);
listId.add(39);
List<MyUser> listByForeach = dao.selectUserByForeach(listId);
System.out.println("foreach元素===============");
for (MyUser myUser : listByForeach){
System.out.println(myUser);
}
<!-- 使用bind元素进行模糊查询-->
<select id="selectUserByBind" resultType="cn.test.beans.MyUser" parameterType="cn.test.beans.MyUser">
<!--bind中的uname是cn.test.beans.MyUser的属性名 -->
<bind name="paran_uname" value="'%' + uname + '%'"/>
select * from user where uname like #{paran_uname}
</select>