动态sql: sql的内容是变化的,可以根据条件获取到不同的sql语句。主要是where部分发生变化。
一、foreach
<foreach> 循环java中的数组, list集合的。主要用在sql的in语句中。
collection="集合类型(list、array)"
item="集合中的成员"
open="开始字符"
close="结束字符"
separator="集合成员之间的分隔符"
1.1 例子
接口:
/* 使用foreach动态sql */
List<Student> selectStudentForeach(List<Integer> list);
xml:
<!-- foreach
<foreach> 循环java中的数组, list集合的。主要用在sql的in语句中。
collection="集合类型(list、array)"
item="集合中的成员"
open="开始字符"
close="结束字符"
separator="集合成员之间的分隔符"
-->
<select id="selectStudentForeach" resultType="Student">
/* 引入sql */
<include refid="studentSql" /> where id in
<foreach collection="list" item="myId" open="(" close=")" separator=",">
#{myId}
</foreach>
</select>
测试类:
@Test
public void testSelectStudentForeach() {
/*
* 使用mybatis的动态代理机制,使用sqlSession.getMapper(dao接口)
* getMapper()获取dao接口对于的实现类对象
*/
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//获得实现类
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
//参数
List<Integer> list = new ArrayList<>();
list.add(1001);
list.add(1002);
//使用方法
List<Student> students = studentDao.selectStudentForeach(list);
//打印
students.forEach(stu1 -> System.out.println(stu1));
//关闭
sqlSession.close();
}
1.2 例子
接口:
/* 使用foreach动态sql 灵活性一*/
List<Student> selectStudentForeach2Student(List<Student> list);
xml:
<!-- <!– foreach 灵活性一 –>
<select id="selectStudentForeach2Student" resultType="Student">
/* 引入sql */
<include refid="studentSql" /> where id in
<foreach collection="list" item="myStu" open="(" close=")" separator=",">
#{myStu.id}
</foreach>
</select>-->
<!-- foreach 灵活性二 -->
<select id="selectStudentForeach2Student" resultType="Student">
/* 引入sql */
<include refid="studentSql" /> where id in (
<foreach collection="list" item="myStu">
#{myStu.id} ,
</foreach>
-1 )
</select>
测试类:
@Test
public void testSelectStudentForeach2Student() {
/*
* 使用mybatis的动态代理机制,使用sqlSession.getMapper(dao接口)
* getMapper()获取dao接口对于的实现类对象
*/
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//获得实现类
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
//参数
List<Student> list = new ArrayList<>();
Student s1 = new Student();
s1.setId(1001);
Student s2 = new Student();
s2.setId(1002);
list.add(s1);
list.add(s2);
//使用方法
List<Student> students = studentDao.selectStudentForeach2Student(list);
//打印
students.forEach(stu1 -> System.out.println(stu1));
//关闭
sqlSession.close();
}