Mybatis总体机制概括
概念说明这里数据输入具体是指上层方法(例如Service方法)调用Mapper接口时,数据传入的形式。
- 简单类型:只包含一个值的数据类型
基本数据类型:int、byte、short、double等
基本数据类型的包装类型:Integer、Character、Double等
字符串类型:String
- 复杂类型:包含多个值的数据类型
实体类类型:Employee、Department等
集合类型:List、Set、Map等
数组类型:int[]、String[]等
复合类型:List、实体类中包含集合等
①Mapper接口中抽象方法的声明
Employee selectEmployee(Integer empId);
②SQL语句
实体类类型参数
①Mapper接口中抽象方法的声明
int insertEmployee(Employee employee);
②SQL语句
insert into t_emp(emp_name,emp_salary) values (#{empName},#{empSalary})
③对应关系
- 现在在这条SQL语句中,#{}中的表达式需要被用来从Employee employee实体类中获取emp_name以及emp_salary的值
- 我们从实体类中获取值通常都是调用getXxx()方法
而getXxx()方法,setXxx()方法定义了实体类的属性 - 定义属性的规则是:把get、set去掉,剩下的部分首字母小写
- 所以我们在#{}使用getXxx()方法,setXxx()方法定义属性就行
④结论
Mybatis会根据#{}中传入的数据,加工成getXxx()方法,通过反射在实体类对象中调用这个方法,从而获取到对应的数据。填充到#{}这个位置。
零散的简单类型数据使用@Param注解实现对零散的简单的数据类型的对应(也就是对应#{}里面的内容)
①Mapper接口中抽象方法的声明
int updateEmployee(@Param("empId") Integer empId,@Param("empSalary") Double empSalary);
②SQL语句
Map类型参数update t_emp set emp_salary=#{empSalary} where emp_id=#{empId}
map类型输入参数通过参数的key值跟SQL语句中#{}占位符对应
①Mapper接口中抽象方法的声明
int updateEmployeeByMap(MapparamMap);
②SQL语句
update t_emp set emp_salary=#{empSalaryKey} where emp_id=#{empIdKey}
③junit测试
@Test
public void testUpdateEmpNameByMap() {
SqlSession session = sessionFactory.openSession();
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
Map paramMap = new HashMap<>();
paramMap.put("empSalaryKey", 999.99);
paramMap.put("empIdKey", 5);
int result = mapper.updateEmployeeByMap(paramMap);
System.out.println("result = " + result);
}
④使用场景
有很多零散的参数需要传递,但是没有对应的实体类类型可以使用。使用@Param注解一个一个传入又太麻烦了。所以都封装到Map中。



