前言
Mybatis的接口方法中可以接受各种各样的参数,按照参数个数可以划分为单参数和多参数方法,参数的类型也有所不同,Mybatis底层对这些参数执行不同的封装方法。
所以,我们在使用时要根据具体情况加入注解。
提示:以下是本篇文章正文内容,下面案例可供参考
一、单参数
- POJO类型:直接使用,实体类属性名和参数占位符名称保持一致。
//Mapper接口中的方法,根据id进行select
public Brand selectById(int id);
//Mapper映射文件中的SQL语句
<select id="selectById">
select *
from tb_brand
where id = #{id}; //实体类属性名和参数占位符名称一样
</select>
- Map集合:直接使用,键名和参数占位符名称保持一致。
//Mapper接口中的方法,map中存放了多个条件,根据这些对select结果进行筛选
public List<Brand> selectByCondition(Map map);
//Mapper映射文件中的SQL语句,可以根据键名映射到对应的参数占位符上
<select id="selectByCondition">
select *
from tb_brand
<where>
<if test="status != null">
and status = #{status}
</if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
</if>
<if test="brandName != null and brandName != '' ">
and brand_name like #{brandName};
</if>
</where>
</select>
- Array集合:Mybatis将数组封装为Map集合。有点难理解,结合下面的代码进行解释,调用deleteByIds(ids)方法,则Mybatis使用了map.put(“array”, ids)和map.put(“arg0”, ids)将数组封装在一个map中,那么我们需要获取数组的元素时,要指定map的key值,以便程序能从map中找出ids数组。
参数前未加注解:
//Mapper接口方法的参数是数组类型
public void deleteByIds(int[] ids);
//Mapper映射文件中的SQL语句,可以根据键名array映射到ids数组上
<delete id="deleteByIds">
delete from tb_brand
where id in
<foreach collection="array" item="id" separator="," open="(" close=");">
#{id}
</foreach>
</delete>
参数前加上注解:
//添加注解后,相当于给map的key值改了名,将array改成了ids
public void deleteByIds(@Param("ids") int[] ids);
//可以根据键名ids映射到ids数组上
<delete id="deleteByIds">
delete from tb_brand
where id in
<foreach collection="ids" item="id" separator="," open="(" close=");">
#{id}
</foreach>
</delete>
加上注解有什么好处呢?答案是更加直观。collection="ids"看起来是不是比collection="array"更舒服些?我们通过@Param("ids")给key值重新起了个名,从而提高了可读性。
- Collection集合:封装为Map集合。
- List集合:封装为Map集合。
- 其他类型:直接使用。
二、多参数
封装成Map集合。还是以下面代码为例进行解释,执行select()方法后,Mybatis会使用map.put("username", "username"),map.put("password", "password")对多个参数进行封装。使用注解方便填充占位符时获取对应值
代码如下(示例):
//Mapper接口方法有多个参数
public User select(@Param("username") String username, @Param("password") String password);
//Mapper映射文件中的SQL语句,可以根据键名获取对应值
<select id="select" resultType="com.jojo.tables.User">
select * from tb_user
where username = #{username} and password = #{password};
</select>
总结
使用@Param注解来修改Map集合中的默认键名,并使用修改后的名称来获取值,这样可读性更高!