动态sql
sql的内容是变化的,可以根据条件获取到不同的sql语句
主要是where部分发生变化
动态sql的实现,使用的时mybatis提供的标签,
1)if是判断条件的
语法:
<if test="判断一个java对象的属性值">
部分sql语句
</if>
使用参数java对象的属性值作为判断条件,语法 属性=xxx值
public List<Student> selectStudentIf( Student student);
2) where 用来包含 多个if的
当多个if有一个成立的, where会自动增加一个where关键字
并去掉 if中多余的 and,or等
<select id="selectStudentIf" resultType="com.sdyu.entity.Student">
select id,name,password from student
where 1=1
<if test="name !=null and name !='' ">
and name=#{name}
</if>
<if test="password !=null and password !='' ">
and password > #{password}
</if>
</select>
3)foreach循环java中的数组、list集合的
主要用在sql的in语句中。
例
学生id是 1001,1002,1003的三个学生
select * from student where id in{1001,1002,1003}
public List selectFor(List idlist)
List list =new ····
list.add(1001);
list.add(1002);
list.add(1003);
dao.selectFor(list);
<foreach collection="" item="" close="" separator=""></foreach>
collection:表示接口中的方法参数的类型,如果 是数组使用array,如果是list集合使用list
item:自定义的,表示数组和集合 成员的变量
open:循环 的开始时的字符
close:循环结束时的字符
separator:集合成员之间的分隔符
接口1
public List<Student> selectForeachOne(List<Integer> list);
mapper1
<select id="selectForeachOne" resultType="com.sdyu.entity.Student">
select * from student where id in
<foreach collection="list" item="myid" open="(" close=")" separator=",">
#{myid}
</foreach>
</select>
实现1
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
List<Integer> list = new ArrayList<>();
list.add(1001);
list.add(1002);
list.add(1003);
List<Student> students = dao.selectForeachOne(list);
for (Student stu:students) {
System.out.println("foreach--one ==="+stu);
}
接口2
public List<Student> selectForeachTwo(List<Student> list);
mapper2
<select id="selectForeachTwo" resultType="com.sdyu.entity.Student">
select * from student where id in
<foreach collection="list" item="stu" open="(" close=")" separator=",">
#{stu.id}
</foreach>
</select>
实现2
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
List<Student> stuList = new ArrayList<>();
Student s1 =new Student();
s1.setId(1002);
stuList.add(s1);
s1 = new Student();
s1.setId(1005);
stuList.add(s1);
List<Student> students = dao.selectForeachTwo(stuList);
for (Student stu:students) {
System.out.println("foreach--one ==="+stu);
}
}
4)动态sql之代码片段
sql标签用于定义sql片段,以便其它sql标签复用,而其他标签使用该sql片段,需要使用include子标签,该标签可以定义sql语句中的任何部分,所以include子标签可以放在动态sql的任何位置。
<sql id=" "> sql语句</sql>
<include refid=" "/>
接口方法:
List<Student> selectStudentSqlFragment(List<Student> stuList);
mapper文件:
<sql id="studentSql">
select id,name,password from student <!-- 重复部分 -->
</sql>
<select id="selectStudentSqlFragment">
<include refid="studentSql"/>
<if test=" "></if>
where id in
<foreach collection="list" open="(" close=")" item="stuobject" separator="," >
#{stuobject.id}
</foreach>
</select>