Mybatis动态SQL - 使用xml配置

Mybatis动态SQL - 使用xml配置

Mybatis支持动态的拼接sql语句,以完成动态的业务逻辑,简化开发。查询数据库中tb_student的数据。

1. Student.java

2. Mapper.xml中通常配置: 配置resultMap用以声明数据库查询结果与实体类之间的映射关系。

	  
	  	
	  	
	  	
	  	
	  	
	  

: 如果传入的参数列表中‘age’不为空,则会在sql语句中加上if语句体中声明的sql语句片段。

	 
	 	select * from tb_student 
		
			
				where name = #{name}
			
			
				where school = #{school}
			
			
				where class = #{grade}
			
		 	
	 
	@Test
	public void testFind2(){
		StudentMapper studentMapper = (StudentMapper) sqlSession.getMapper(StudentMapper.class);
		Map map = new HashMap();
		map.put("name",null);
		map.put("grade", "ad");
		map.put("school", "sd");
 		List students = studentMapper.findStudentUsingChose(map);
 		for (Student student : students){ 			
 			if(student != null){
 				System.out.println("select success! "+student);
 			}
 		}
		sqlSession.commit();
	}

遍历传入的参数列表

	   
	@Test
	public void testFind3(){
		StudentMapper studentMapper = (StudentMapper) sqlSession.getMapper(StudentMapper.class);
		Map map = new HashMap();
		List nameList = new ArrayList();
		nameList.add("Robin");
		nameList.add("Mary");
		map.put("nameList", nameList);
 		List students = studentMapper.findStudentList(map);
 		for (Student student : students){ 			
 			if(student != null){
 				System.out.println("select success! "+student);
 			}
 		}
		sqlSession.commit();
	}

添加前缀/后缀

	  
	@Test
	public void testFind4(){
		StudentMapper studentMapper = (StudentMapper) sqlSession.getMapper(StudentMapper.class);
		Map map = new HashMap();
		map.put("name",null);
		map.put("age", 23);
 		List students = studentMapper.findStudentList2(map);
 		for (Student student : students){ 			
 			if(student != null){
 				System.out.println("select success! "+student);
 			}
 		}
		sqlSession.commit();
	}

 

你可能感兴趣的:(Mybatis)