<!--根据条件查询--> <selectid="finduserCondition"resultMap="userMap"parameterType="user"> select * from user where 1=1 <iftest="userName != null"> and username = #{userName} </if> <iftest="userSex != null"> and sex = #{userSex} </if> </select>
User u = new User(); u.setUserName("老王"); u.setUserSex("男"); //5.使用代理对象执行方法 List<User> users = userDao.finduserCondition(u); for (User user : users) { System.out.println(user); }
}
==测试结果:==
动态 SQL 之where标签
为了简化上面 where 1=1 的条件拼装,我们可以采用<where>标签来简化开发。
持久层 Dao 映射配置
1 2 3 4 5 6 7 8 9 10 11
<selectid="finduserCondition"resultMap="userMap"parameterType="user"> select * from user <where> <iftest="userName != null"> and username = #{userName} </if> <iftest="userSex != null"> and sex = #{userSex} </if> </where> </select>
效果和上面的if标签一样
动态 SQL 之foreach标签
需求
传入多个 id 查询用户信息,用下边两个 sql 实现: SELECT * FROM USERS WHERE username LIKE ‘%王%’ AND (id =10 OR id =19 OR id=36) SELECT * FROM USERS WHERE username LIKE ‘%王%’ AND id IN (10,19,36) 这样我们在进行范围查询时,就要将一个集合中的值,作为参数动态添加进来。
<!--根据QueryVo中的id集合实现查询查询用户列表--> <selectid="findUserInIds"resultMap="userMap"parameterType="queryvo"> <includerefid="defaultUser"></include> <where> <iftest="ids!=null and ids.size()>0"> <foreachcollection="ids"open = "and id in ("close=")"item="uid"separator=","> #{uid} </foreach>
<!--根据QueryVo中的id集合实现查询查询用户列表--> <selectid="findUserInIds"resultMap="userMap"parameterType="queryvo"> <includerefid="defaultUser"></include> <where> <iftest="ids!=null and ids.size()>0"> <foreachcollection="ids"open = "and id in ("close=")"item="uid"separator=","> #{uid} </foreach>