一:使用动态SQL完成多条件查询
a:使用if+where实现多条件查询
首先场景需求,有 个年级和班级表,第一个要求是根据模糊查询姓名,和年龄大小进行条件查询,接口层方法
public List getStudentByIf(student stu);
其次是映射文件的配置
测试
studentDao dao = MyBatis.getSessionTwo().getMapper(studentDao.class);
student stu = new student();
stu.setStuName("z");
// stu.setStuAge(19);
List list= dao.getStudentByIf(stu);
for (student item:list) {
System.out.println("----------"+item.getStuName());
} 打印效果
----------zhangyu----------zy----------zy----------zhang
b:choose when 分类
这种方式和java中choose循环结构原理是一样的,判断多种情况,只要修改一下映射文件即可
接口 类
public List getAllStudentByLike(Map userMap); //使用map作为参数
映射文件
结果
zhangyu
zy
zy
zhang
c:使用foreach完成复杂 查询,有三种方式,
第一种:传入的参数为数组类型
//传一组 xueshengID
public List getStudentBystuId_foreach_array(Integer[] ints);
映射文件配置
测试类
Integer[] ints = {2,3,4};
List list = dao.getStudentBystuId_foreach_array(ints);
for (student item:list) {
System.out.println(item.getStuName());
}
第二种:传入list集合
public List getStudentBystuId_foreach_list(List list);
测试:
studentDao dao = MyBatis.getSessionTwo().getMapper(studentDao.class);
Integer ints = 2;
List list = new ArrayList();
list.add(ints);
List stulist = dao.getStudentBystuId_foreach_list(list);
for (student item:stulist) {
System.out.println(item.getStuName());
}
第三种:根据Map集合
public List getStudentBystuId_foreach_map(Map stuMap);
Map stumap = new HashMap();
List listStuId = new ArrayList();
listStuId.add(2);
listStuId.add(3);
listStuId.add(4);
stumap.put("stuId",listStuId);
List list = dao.getStudentBystuId_foreach_map(stumap);
for (student item:list
) {
System.out.println(item.getStuName());
}
打印结果可以执行以下。
d;一对多的两种实现方式
主要是resultMapper里的配置不同
接口方法
public grade getGradeById(int gradeId);
映射文件配置
@Test
public void TestConn(){
gradeDao dao = MyBatis.getSessionTwo().getMapper(gradeDao.class);
grade grade = dao.getGradeById(1);
for (student item:grade.getGatStudent() ) {
System.out.println(item.getStuName());
}
}
两种方式都能实现,打印效果
方案一打印效果
==> Preparing: select * from grade,student where grade.gradeId = student.stuGrade and gradeId = ? ============一条sql
==> Parameters: 1(Integer)
<== Columns: gradeId, gradeName, stuId, stuName, stuAge, stuGrade
<== Row: 1, S1297, 2, zhangyu, 19, 1
<== Row: 1, S1297, 3, zy, 20, 1
<== Row: 1, S1297, 4, zy, 21, 1
<== Total: 3
zhangyu
zy
zy
Process finished with exit code 0
方案二打印效果
==> Preparing: select * from grade where gradeId=? ==========第一条sql
==> Parameters: 1(Integer)
<== Columns: gradeId, gradeName
<== Row: 1, S1297
====> Preparing: select * from student where stuGrade = ? ==========第二条sql
====> Parameters: 1(Long)
<==== Columns: stuId, stuName, stuAge, stuGrade
<==== Row: 2, zhangyu, 19, 1
<==== Row: 3, zy, 20, 1
<==== Row: 4, zy, 21, 1
<==== Total: 3
<== Total: 1
zhangyu
zy
zy
Process finished with exit code 0