1. 单个简单类型参数
简单类型包括: 当接口中的方法的参数只有一个(单个参数),并且参数的数据类型都是简单类型。 ListselectById(Long id); parameterType属性的作用: 告诉mybatis框架,我这个方法的参数类型是什么类型。 mybatis框架自身带有类型自动推断机制,所以大部分情况下parameterType属性都是可以省略不写的。 SQL语句最终是这样的: select * from t_student where id = ? JDBC代码是一定要给?传值的。 怎么传值?ps.setXxx(第几个问号, 传什么值); ps.setLong(1, 1L); ... mybatis底层到底调用setXxx的哪个方法,取决于parameterType属性的值。 注意:mybatis框架实际上内置了很多别名。可以参考开发手册。 通过测试得知,简单类型对于mybatis来说都是可以⾃动类型识别的: 也就是说对于mybatis来说,它是可以⾃动推断出ps.setXxxx()⽅法的。ps.setString()还是 ps.setInt()。它可以⾃动推断。
2. Map参数
保存学生信息,通过Map参数。以下是单个参数。但是参数的类型不是简单类型。是Map集合。 int insertStudentByMap(Mapmap); insert into t_student(id,name,age,sex,birth,height) values(null,#{姓名},#{年龄},#{性别},#{生日},#{身高})
@Test
public void testInsertStudentByMap(){
SqlSession sqlSession = SqlSessionUtil.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Map map = new HashMap<>();
map.put("姓名", "赵六");
map.put("年龄", 20);
map.put("身高", 1.81);
map.put("性别", '男');
map.put("生日", new Date());
mapper.insertStudentByMap(map);
sqlSession.commit();
sqlSession.close();
}
这种⽅式是⼿动封装Map集合,将每个条件以key和value的形式存放到集合中。然后在使⽤的时候通过# {map集合的key}来取值
3.实体类参数
这⾥需要注意的是:#{} ⾥⾯写的是属性名字。这个属性名其本质上是:set/get⽅法名去掉set/get之后 的名字
4.多参数
/**
* 这是多参数。
* 根据name和sex查询Student信息。
* 如果是多个参数的话,mybatis框架底层是怎么做的呢?
* mybatis框架会自动创建一个Map集合。并且Map集合是以这种方式存储参数的:
* map.put("arg0", name);
* map.put("arg1", sex);
* map.put("param1", name);
* map.put("param2", sex);
*/
List selectByNameAndSex(String name, Character sex);
注意:低版本的mybatis中,使用的是:#{0}和#{1},以及#{2}... 高版本的mybatis中,使用的是: #{arg0} 和 #{arg1},或者 #{param1}和 #{param2} 但是这种方式的可读性太差,因此可以使用注解@Param注解告诉MyBatis
5.@Param注解(命名参数)
* Param注解。核⼼:@Param("这⾥填写的其实就是map集合的key")
* mybatis框架底层的实现原理,就会变成:
* map.put("name", name);
* map.put("sex", sex);
*/
List selectByNameAndSex2(@Param("name") String name, @Param("sex") Character sex);