参考文档:https://juejin.cn/post/7034710425891504135

MyBaits参数传递

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

单个参数

:::info MyBatis提供了 ParamNameResolver类来进行参数封装 :::

  1. POJO类型:直接使用.属性名 和 参数占位符名称 一致
  2. Map集合:直接使用,键名 和 参数占位符名称 一致
  3. Collection:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名

map.put(“arg0”,collection集合)
map.put(“collection,collection集合”)

  1. List:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名

map.put(“arg0”,list集合)
map.put(“collection”,list集合)
map.put(“list”,list集合)

  1. Array:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名

map.put(“arg0”,数组)
map.put(“array”,数组)

  1. 其他类型:直接使用

    多个参数

    ```java //封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名

map.put(“arg0”,参数值1)

map.put(“param1”,参数值1)

map.put(“param2”,参数值2)

map.put(“agr1”,参数值2)

//————————-@Param(“username”)

map.put(“username”,参数值1)

map.put(“param1”,参数值1)

map.put(“param2”,参数值2)

map.put(“agr1”,参数值2)

  1. <a name="Rotrn"></a>
  2. # 注解开发
  3. <a name="Vs9Ls"></a>
  4. ## 注解完成增删改查
  5. :::info
  6. 使用注解开发会比配置文件开发更加方便
  7. :::
  8. @Select<br />@Insert<br />@Update<br />@Delete
  9. <a name="Fiqem"></a>
  10. ### 提示
  11. - 注解完成简单功能
  12. - 配置文件完成复杂功能
  13. <a name="TNqHf"></a>
  14. ## 简单举例
  15. ```java
  16. @Select("select * from tb_user where id = #{id}")
  17. public User selectById(int id);

编写接口方法

:::info 编写BrandMapper.java :::

    @Select("select * from tb_brand where id = #{id}")
    Brand selectById02(int id);

核心配置文件 mybatis-config.xml文件中绑定接口

:::info 以往 是注册mapper.xml文件。但是在实际的开发中还是建议使用Mapper.xml文件 :::

需要在核心配置文件mybatis-config.xml中绑定接口—(映射关系)

<!--    绑定接口-->
    <mappers>
        <mapper class="dao.UserDao"/>
    </mappers>

以前是绑定映射文件Tb_UserMapper.xml(注解就是代替映射文件的—共同点:里面都是sql语句)
— 前面绑定对应的接口是UserMapper.java接口
1.4 Mybatis - MyBatis注解开发SQL举例,以及MyBatis参数传递的一些概念 - 图1
在mybatis-config.xml中绑定映射文件
1.4 Mybatis - MyBatis注解开发SQL举例,以及MyBatis参数传递的一些概念 - 图2

编写测试方法

:::info 编写MyBatisTest.java :::

      @Test
    public void testSelectById02() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();

        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        Brand brand = brandMapper.selectById02(1);

        System.out.println(brand);

        sqlSession.close();

    }