MyBatis参数传递
MyBatis接口方法中可以接收各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式
单个参数:
-
POJO类型:
-
Map集合:
-
Collection:
-
List:
-
Array:
-
其他类型
多个参数:
MyBatis提供了ParamNameResolver类来进行参数封装
UserMapper.xml
<select id="select" resultType="user"> select * from tb_user where username = #{param1} and password = #{param2} </select>
UserMapper.java类
/* ## MyBatis参数传递 MyBatis接口方法中可以接收各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式 单个参数: 1. POJO类型: 2. Map集合: 3. Collection: 4. List: 5. Array: 6. 其他类型 多个参数:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名 map.put("arg0",参数值1) map.put("param1",参数值1) map.put("param2",参数值2) map.put("arg1",参数值2) ----------------------@Param("username") map.put("username",参数值1) map.put("param1",参数值1) map.put("param2",参数值2) map.put("arg1",参数值2) MyBatis提供了ParamNameResolver类来进行参数封装 */ User select(@Param("username") String username, String password);
UserMapperTest测试类
@Test public void testSelect() throws IOException { //1.获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取SqlSession对象 //SqlSession sqlSession = sqlSessionFactory.openSession(); SqlSession sqlSession = sqlSessionFactory.openSession(true); //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(); }
MyBatis参数传递
MyBatis接口方法中可以接收各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式
单个参数:
1. POJO类型:直接使用,属性名和参数占位符名称一致
2. Map集合:直接使用,键名和参数占位符名称一致
3. Collection:封装为Map集合
map.put("arg0",collection集合);
map.put("collection",collection集合);
4. List:
map.put("arg0",list集合);
map.put("collection",list集合);
map.put("list",list集合);
5. Array:封装为map集合
map.put("arg0",数组);
map.put("array",数组);
6. 其他类型: 直接使用
多个参数:封装为Map集合,可以使用
注解哪些地方需要添加:Collection,List,Array,多个参数。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能