MyBatis 接口方法中可以接收各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式
单个参数:
1.POJO类型:
2. Map集合:
3. Collection:
4. List:
5. Array:
6.其他类型:
多个参数:
MyBatis提供了ParamNameResolver类来进行参数封装
/*
*MyBatis 参数封装
单个参数:
1.POJO类型:直接使用,属性名 和 参数占位符名称一致
2. Map集合:直接使用,键名 和 参数占位符名称一致
3. Collection:封装为Map集合,可以使用@Param注解,替换Map集合中的arg键名
* map.put("arg0",collection集合);
* map.put("collection集合",collection集合);
4. List:封装为Map集合,可以使用@Param注解,替换Map集合中的arg键名
* map.put("arg0",list集合);
* map.put("collection集合",list集合);
* map.put("list",list集合);
5. Array:封装为Map集合,可以使用@Param注解,替换Map集合中的arg键名
* map.put("arg0",数组);
* map.put("array",数组);
6.其他类型:直接使用
多个参数:封装为Map集合,可以使用@Param注解,替换Map集合中的arg键名
* map.put("arg0",参数值1)
* map.put("param1",参数值1)
* map.put("arg1",参数值2)
* map.put("param2",参数值2)
* ----------------------------@Param("username")
* map.put("username",参数值1)
* map.put("param1",参数值1)
* map.put("arg1",参数值2)
* map.put("param2",参数值2)
* */
User select(@Param("username")String username, @Param("password")String password);
<select id="select" resultType="com.zxl.pojo.User">
select * from tb_user
where
username = #{username}
and password = #{password}
</select>
@Test
public void select()throws Exception{
//1.加载mybatis的核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.获取Mapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//4.执行方法
String username = "zhangsan";
String password = "123";
User user = userMapper.select(username, password);
System.out.println(user);
//提交事务
sqlSession.commit();
//5.释放资源
sqlSession.close();
}
建议:将来都使用@Param注解来修改Map集合中默认的键名,并使用修改后的名称来获取值,这样可读性更高!