1.当参数是普通类型
主要是动态SQL标签的使用,注意如果parameterType
是List
的话,则在标签体内引用这个List,只能用变量名list
,如果parameterType
是数组
,则只能用变量名array
。
<!-- List<User> findByList(List<Integer> list); -->
<select id="findByList" resultType="com.xia.domo.User" parameterType="java.util.List">
SELECT * FROM user
<where>
<if test="list != null and list.size() > 0">
AND id in
<foreach collection="list" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</if>
</where>
</select>
测试代码:
@Test
public void TestFindByList() throws IOException {
//1.读取配置文件,形成字节输入流
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory对象
SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(in);
//3.SqlSession对象
SqlSession session = factory.openSession();
//4.获取dao的代理对象
IUserDao mapper = session.getMapper(IUserDao.class);
//5.执方法
List<Integer> list = Arrays.asList(1, 49, 51);
List<User> users = mapper.findByList(list);
for (User user1:users){
System.out.println(user1);
}
//6.释放资源
session.close();
in.close();
}
结果:
2.当参数是对象
dao层
/**
* 根据user集合查询
* @param users
* @return
*/
@MapKey("id")//给key赋值
Map<String,Map<String,Object>> findByVoList(List<User> users);
}
xml文件
<!-- Map<String,Map<String,Object>> findByVoList(List<QueryVo> queryVos); -->
<select id="findByVoList" resultType="java.util.Map" parameterType="java.util.List">
SELECT * FROM user
<where>
<if test="list != null and list.size() > 0">
AND id in
<foreach collection="list" item="user" open="(" separator="," close=")">
#{user.id} <!-- 遍历的元素是user,比较的是参数user的id和数据库里面user的id-->
</foreach>
</if>
</where>
</select>
测试代码:
@Test
public void TestFindByQueryList() throws IOException {
//1.读取配置文件,形成字节输入流
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory对象
SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(in);
//3.SqlSession对象
SqlSession session = factory.openSession();
//4.获取dao的代理对象
IUserDao mapper = session.getMapper(IUserDao.class);
//5.执方法
Student student=new Student();
List<User> list = mapper.findByName("狗");
Map<String, Map<String, Object>> byVoList = mapper.findByVoList(list);
System.out.println(byVoList);
//6.释放资源
session.close();
in.close();
}
结果: