<selectid="findUserByCondition"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>
测试
1 2 3 4 5 6 7 8
@Test publicvoidtestFindByCondition(){ User u = new User(); u.setUserName("老王"); u.setUserSex("女");
<selectid="findUserByCondition"resultMap="userMap"parameterType="user"> select * from user <where> <iftest="userName != null"> and username = #{userName} </if> <iftest="userSex != null"> and sex = #{userSex} </if> </where> </select>
foreach标签
根据queryvo中的Id集合实现查询用户列表
QueryVo.java
1 2 3 4 5 6 7 8
publicclassQueryVo{
private User user; private List<Integer> ids;
// get set ... }
IUserDao.java
1
List<User> findUserInIds(QueryVo vo);
IUserDao.xml
1 2 3 4 5 6 7 8 9 10
<selectid="findUserInIds"resultMap="userMap"parameterType="queryvo"> select * from user <where> <iftest="ids != null and ids.size()>0"> <foreachcollection="ids"open="and id in ("close=")"item="uid"separator=","> #{uid} </foreach> </if> </where> </select>
#{uid}是由上面item=”uid”决定的
测试
1 2 3 4 5 6 7 8 9 10 11
@Test publicvoidtestFindInIds(){ QueryVo vo = new QueryVo(); List<Integer> list = new ArrayList<Integer>(); list.add(41); list.add(42); list.add(46); vo.setIds(list);
List<User> users = userDao.findUserInIds(vo); }
sql标签
抽取重复的sql语句
(本来写不写;都可以,但是抽取sql语句时,为了防止后续的拼接出问题,最好不要写;)
1 2 3
<sqlid="defaultUser"> select * from user </sql>
就可以把
1 2 3
<selectid="findAll"resultMap="userMap"> select * from user </select>