实现功能
(1)多条件查询。
当用户输入的学生姓名不为空时,则只根据学生姓名进行学生信息的查询。
当用户输入的学生姓名为空而学生专业不为空时,则只根据学生专业进行学生信息的查询。
当用户输入的学生姓名和专业都为空,则要求查询出所有学号不为空的学生信息。
(2)单条件查询出所有id值小于5的学生的信息。
一、准备工作
1、创建student数据表
2、创建工程
3、引入依赖
4、创建相关配置文件
(1)核心配置文件mybatis-config.xml
(2)核心配置文件使用的db.properties文件
(3)log4j.xml文件
5、创建用户配置文件
(1)创建pojo实体类
(2)创建mapper接口类
(3)创建util工具类
(4)在resources下创建com/biem/mapper文件夹并创建StudentMapper.xml映射文件
6、创建测试类文件
二、多条件查询 <choose>(<when>、<otherwise>)
当用户输入的学生姓名不为空时,则只根据学生姓名进行学生信息的查询。
当用户输入的学生姓名为空而学生专业不为空时,则只根据学生专业进行学生信息的查询。
当用户输入的学生姓名和专业都为空,则要求查询出所有学号不为空的学生信息。
1. com.biem.mapper.CustomerMapper.class中添加方法
public List<Student> findStudentByChoose(Student student);
2. com/biem/mapper/CustomerMapper.xml中添加sql语句
<select id="findStudentByChoose" parameterType="student" resultType="student">
select * from student where
<choose>
<when test="name!=null and name!=''">
name like concat('%',#{name},'%')
</when>
<when test="name=null and profession!=null">
and profession=#{profession}
</when>
<otherwise>
and id is not null
</otherwise>
</choose>
</select>
3.在com.biem.test.TestMybatis.java添加测试方法
@Test
public void testFindStudentByChoose(){
SqlSession session = MybatisUtil.openSession();
StudentMapper mapper = session.getMapper(StudentMapper.class);
Student student =new Student();
student.setName("九儿");
List<Student> students = mapper.findStudentByChoose(student);
System.out.println("students = "+ students);
session.close();
}
4.测试结果
二、单条件查询<if>
单条件查询出所有id值小于5的学生的信息。
1. com.biem.mapper.CustomerMapper.class中添加方法
public List<Student> findStudentById(Student student);
2. com/biem/mapper/CustomerMapper.xml中添加sql语句
<select id="findStudentById" parameterType="student" resultType="student">
select * from student where
<if test="id!=null and id=''">
id limit 5
</if>
</select>
3.在com.biem.test.TestMybatis.java添加测试方法
@Test
public void testFindStudentById(){
SqlSession session = MybatisUtil.openSession();
StudentMapper mapper = session.getMapper(StudentMapper.class);
Student student =new Student();
List<Student> list = mapper.findStudentById(student);
System.out.println("list = "+list);
session.close();
}