MyBatis--6.多条件查询问题

1,890 阅读2分钟

​ 当查询条件不只一个又不能封装成一个对象的时候,SQL语句中怎么获取到对应的值;

​ 例如:想要查询名字中带有‘张’并且年龄大于23的学生,又不想直接封装成一个student对象;

​ 可以使用以下两种方式进行处理:

使用Map进行封装:

​ 可以将需要传递的多个参数使用Map进行封装,在mapper中可以使用map的key直接获取到对应的value

	//在TestStudentDao中,将需要查询的数据封装到map中
	@Test
	public void testSelectAllStudent() {
		Map<String , Object> map = new HashMap<String,Object>();
		//查询名字中由‘张’的,并且年龄大于23的学生
		map.put("nameCon", "张");
		map.put("ageCon", 23);
		List<Student> studentList = dao.selectStudentByConditionMap(map);
		for (Student student : studentList) {
			System.out.println(student);
		}
	}
=========================================================================================
    //在StudentDao中创建对应的方法
    List<Student> selectStudentByConditionMap(Map<String,Object> map);
=========================================================================================
    //修改mapper.xml,MyBatis中可以通过map的key直接获取到对应的value,例如这里的#{nameCon}
    <select id="selectStudentByConditionMap" resultType="com.mybatis.beans.Student">
		select id,name,age,score 
		from student 
		where name like '%' #{nameCon} '%' and age > #{ageCon}
	</select>

使用参数的索引号进行获取:

	//在TestStudentDao调用selectStudentByConditionIndex方法
	@Test
	public void testSelectStudentByConditionIndex() {
		// 查询名字中由‘张’的,并且年龄大于23的学生
		List<Student> studentList = dao.selectStudentByConditionIndex("张", 23);
		for (Student student : studentList) {
			System.out.println(student);
		}
=========================================================================================
	//在StudentDao中添加对应的方法    
   List<Student> selectStudentByConditionIndex(String name, int age);
=========================================================================================
    //在mapper中添加对应的SQL语句,当传递的参数有多个时,可以使用其下标进行标识
    <select id="selectStudentByConditionIndex" resultType="com.mybatis.beans.Student">
		select
		id,name,age,score
		from student
		where name like '%' #{0} '%' and age > #{1}
	</select>

总结: #{}可以放什么内容?

1)参数对象的属性 2)随意内容,但此时的#{}是个占位符 3)参数为map时的key 4)参数为map时,若key所对应的value为对象,则可将该对象的属性放入 5)参数的索引号

​ 在mapper中,对于传递的参数只有一个的情况下,#{}中可以是任意的值,因为它的作用是一个占位符;

​ 如果有传递的值有多个,可以使用其索引值进行标识;

​ 如果传递的map中key所对应的值为对象,则可以在mapper中通过#{key.属性名}来获取相应的数据

例如:

	Map<String , Object> map = new HashMap<String,Object>();
	Student stu = new Student();
	stu.setScore(95);
	map.put("stu",stu);
	map.put("nameCon","张");
	List<Student> studentList = dao.selectStudentByConditionMap(map);	

​ 则在mapper中可以通过#{key.属性名}获取

		<!--获取对象中属性值: #{stu.score}-->
		select
		id,name,age,score
		from student
		where name like '%' #{nameCon} '%' and score > #{stu.score}