首先定义queryVo 类
package com.itheima.domain; import java.util.List; public class QueryVo { private User user; private List<Integer> ids; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List<Integer> getIds() { return ids; } public void setIds(List<Integer> ids) { this.ids = ids; } }
IUserDao定义的接口
/* * 根据传入参数条件查询 * @param user 查询的条件:有可能有用户名,有可能有性别,也有可能有地址,可能啥都没有 * */ List<User> findUserByCondition(User user); /* * 根据queryVo中提供的id集合查询用户信息 * */ List<User> findUserInIds(QueryVo vo);
根据条件进行查询 IUserDao.xml
<!--根据条件查询--> <select id="findUserByCondition" parameterType="com.itheima.domain.User" resultMap="userMap"> select * from USER <where> <if test="username != null"> and username = #{username} </if> <if test="sex != null"> and sex = #{sex} </if> </where> </select> <!--根据queryVo中的Id集合实现查询用户列表--> <select id="findUserInIds" parameterType="com.itheima.domain.QueryVo" resultMap="userMap"> select * from user <where> <if test="ids != null and ids,size()>0"> <foreach collection="ids" open="and id in (" close=")" item="id" separator=","> #{id} </foreach> </if> </where> </select>
测试
@Test public void testFindUserByCondition(){ User u = new User(); u.setUsername("老王"); List<User> users = userDao.findUserByCondition(u); for(User user:users) System.out.println(user); } @Test public void testFindInIds(){ QueryVo vo = new QueryVo(); List<Integer> list = new ArrayList<>(); list.add(41); list.add(42); list.add(46); vo.setIds(list); List<User> users = userDao.findUserInIds(vo); for(User user:users) System.out.println(user); }