一、需求分析
本案例要求利用本章所学知识完成一个学生信息查询系统,该系统要求实现2个以下功能。
1)单条件查询
查询出所有id值小于5的学生的信息;
2)多条件查询
当用户输入的学生姓名不为空,则只根据学生姓名进行学生信息的查询;
当用户输入的学生姓名为空,而学生专业不为空,则只根据学生专业进行学生信息的查询;
二、资料、视频教程
学生信息查询系统
三、编码实现
1、搭建环境
1)数据库环境
mybatis数据库,t_student表
2)引入依赖
pom.xml文件
3)数据库连接的配置文件
src/main/resources,数据库连接的配置文件db.properties。
4)MyBatis核心配置文件
src/main/resources,MyBatis的核心配置文件mybatis-config.xml
5)数据封装类
src/main/java,新建com.sw.pojo包,新建Student类
public class Student {
private Integer id;
private String name;
private String major;
private String sno;
//get、set
//tostring
}
6)mapper接口
src/main/java创建com.sw.mapper包,新建StudentMapper接口。
7)映射文件
src/main/resources目录下,新建com/sw/mapper目录,StudentMapper.xml
2、单条件查询
查询出所有id值小于5的学生的信息
1)修改接口StudentMapper
List<Student> getListByIdCondition(List<Integer> ids);
2)修改映射文件CustomerMapper.xml
<select id="getListByIdCondition" parameterType="java.util.List" resultType="Student">
select * from t_student where id in
<foreach collection="list" index="index" open="(" separator="," close=")" item="id">
#{id}
</foreach>
</select>
3)测试
使用工具类MyBatisUtils的getSession方法来获得sqlSession
public void testGetListByIdCondition() {
List<Integer> ids = new ArrayList<Integer>();
for (int i = 1; i < 5; i++) {
ids.add(i);
}
List<Student> studentList = studentMapper.getListByIdCondition(ids);
for (Student student:studentList) {
System.out.println(student);
}
}
3、多条件查询
当用户输入的学生姓名不为空,则只根据学生姓名进行学生信息的查询;
当用户输入的学生姓名为空,而学生专业不为空,则只根据学生专业进行学生信息的查询;
否则返回学号不为空的学生信息
1)修改接口CustomerMapper
List<Student> getListByStudent(Student student);
2)修改映射文件CustomerMapper.xml
<select id="getListByStudent" parameterType="Student" resultType="Student">
select * from t_student
<where>
<choose>
<when test="name !=null and name !=''">
and name like concat('%',#{name}, '%')
</when>
<when test="major !=null and major !=''">
and major= #{major}
</when>
<otherwise>
and sno is not null
</otherwise>
</choose>
</where>
</select>
3)测试
public void testGetListByChoose() {
Student student = new Student();
// student.setName("张");
// student.setMajor("英语");
List<Student> studentList = studentMapper.getListByChoose(student);
for (Student s:studentList) {
System.out.println(s);
}
}