参考文档:https://juejin.cn/post/7034710425891504135
MyBaits参数传递
MyBatis接口方法中可以接收各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式
单个参数
:::info MyBatis提供了 ParamNameResolver类来进行参数封装 :::
- POJO类型:直接使用.属性名 和 参数占位符名称 一致
- Map集合:直接使用,键名 和 参数占位符名称 一致
- Collection:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名
map.put(“arg0”,collection集合)
map.put(“collection,collection集合”)
- List:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名
map.put(“arg0”,list集合)
map.put(“collection”,list集合)
map.put(“list”,list集合)
- Array:封装为Map集合,可以使用@Param注解,替换Map集合中默认的arg键名
map.put(“arg0”,数组)
map.put(“array”,数组)
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)
<a name="Rotrn"></a># 注解开发<a name="Vs9Ls"></a>## 注解完成增删改查:::info使用注解开发会比配置文件开发更加方便:::@Select<br />@Insert<br />@Update<br />@Delete<a name="Fiqem"></a>### 提示- 注解完成简单功能- 配置文件完成复杂功能<a name="TNqHf"></a>## 简单举例```java@Select("select * from tb_user where id = #{id}")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接口
在mybatis-config.xml中绑定映射文件
编写测试方法
:::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();
}
