MyBatis参数传递

MyBatis参数传递

MyBatis接口方法中可以接收各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式

单个参数:

  1. POJO类型:

  1. Map集合:

  2. Collection:

  3. List:

  4. Array:

  5. 其他类型

多个参数:

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集合,可以使用@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类来进行参数封装

注解哪些地方需要添加:Collection,List,Array,多个参数。

建议:将来都使用@Param注解来修改Map集合中默认的键名,并使用修改后的名称来获取键值,这样可读性更高。

posted @ 2022-05-11 21:40  Resign~as  阅读(55)  评论(0)    收藏  举报