JavaWeb:MyBatis(10)参数传递

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集合中默认的键名,并使用修改后的名称来获取值,这样可读性更高!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值