示例【根据姓名和班级查询学生信息】
创建t_student表
配置StudentMapper.xml
<select id="getStudentByNameAndClasses" resultType="com.po.Student">
select * from t_student where 1=1
<choose>
<when test="sname!=null">
and sname like concat('%',#{sname},'%')
</when>
<when test="classes!=null">
and classes=#{classes}
</when>
<otherwise>
and address is not null
</otherwise>
</choose>
</select>
创建StudentDao
package com.dao;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import com.factory.SessionFactory;
import com.po.Student;
public class StudentDao {
private SqlSession session=SessionFactory.getSqlSession();
private List<Student> students=new ArrayList<Student>();
@Test
public void getStudentByNameAndClasses(){
Student stu=new Student();
stu.setSname("张三");
stu.setClasses("大一");
students=session.selectList("com.mapper.StudentMapper.getStudentByNameAndClasses", stu);
for (Student student : students) {
System.out.println(student);
}
}
}
根据姓名和班级查询
根据班级查询
当姓名和班级传递的参数都为空时,默认查询地址不为空的学生信息