1、动态sql
(1)if使用
将mapper文件中改为
<!-- if
<if:test="使用参数java对象的属性值作为判断条件,语法 属性=XXX值">
添加id > 0是因为当第一个不成立时,第二句能够组成完整的sql语句
1=1与id > 0的效果是一样的
-->
<select id="selectStudentIf" resultType="com.bjpowernode.domain.Student">
select <include refid="studentSqlOne" /> from student
where id > 0
<if test="name !=null and name !='' ">
and name = #{name}
</if>
<if test="age > 0">
or age > #{age}
</if>
</select>
(2)where的使用
用来包含 多个的, 当多个if有一个成立的, 会自动增加一个where关键字,并去掉 if中多余的 and ,or等。
<select id="selectStudentWhere" resultType="com.bjpowernode.domain.Student">
<include refid="studentSql" />
<where>
<if test="name !=null and name !='' ">
name = #{name}
</if>
<if test="age > 0">
or age > #{age}
</if>
</where>
</select>
dao接口的方法
//where使用
List<Student> selectStudentWhere(Student student);
测试类为
@Test
public void testSelectStudentIf(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
Student student = new Student();
// student.setName("李四");
// student.setAge(18);
student.setName("李四");
student.setAge(20);
List<Student> students = dao.selectStudentIf(student);
for(Student stu:students){
System.out.println("if==="+stu);
}
(3)foreach的使用
将mapper文件中改为
<!--
collection:表示接口中的方法参数的类型, 如果是数组使用array , 如果是list集合使用list
item:自定义的,表示数组和集合成员的变量
open:循环开始是的字符
close:循环结束时的字符
-->
<select id="selectForeachOne" resultType="com.bjpowernode.domain.Student">
select * from student where id in
<foreach collection="list" item="myid" open="(" close=")" separator=",">
#{myid}
</foreach>
</select>
dao接口方法为
List<Student> selectForeachOne(List<Integer> idlist);
测试类为
@Test
public void testSelectForEach(){
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);
}
}
(4)sql片段
在mapper文件中等上面添加
<!--定义sql片段
id为自定义的-->
<sql id="studentSql">
select id,name, age, email from student
</sql>
<!--
使用<include refid="sql片段的id值"/>即可使用sql片段中的语句
-->
<select id="selectStudentIf" resultType="com.bjpowernode.domain.Student">
select <include refid="studentSqlOne" /> from student
where id > 0
<if test="name !=null and name !='' ">
and name = #{name}
</if>
<if test="age > 0">
or age > #{age}
</if>
</select>