Mybatis方法传多个参数(三种解决方案)

Mybatis的Mapper接口的参数,一般是一个对象,但如果不是对象,并且有多个参数的时候我们应该怎样做呢?

我们的第一个想法是把参数封装成一个java.util.Map类型,然后在方法的注释上面写上map的key是什么,但是,这样的做法明显不够直观,不能够清楚的看出方法的参数是什么,而且影响到了java的多态性(方法名相同,参数数量或类型不同)。

1.多个形参传递多参数
Dao层的函数方法

1
public User selectUser(String name,String area);

对应的Mapper.xml文件

1
2
3
<select id="selectUser" resultMap="BaseResultMap">
select * from user_user where user_name = #{0} and user_area=#{1}
</select>

其中,#{0}代表接收的是dao层中的第一个参数,#{1}代表dao层中第二参数,更多参数以此类推即可。
2.采用Map传递多参数
Dao层的函数方法

1
public User selectUser(Map paramMap);

对应的Mapper.xml文件

1
2
3
<select id="selectUser" resultMap="BaseResultMap">
select * from user_user where user_name = #{userName,jdbcType=VARCHAR} and user_area=#{userArea,jdbcType=VARCHAR}
</select>

Service层调用

1
2
3
4
5
6
private User SelectUser(){
Map paramMap = new hashMap();
paramMap.put(“userName”,”对应具体的参数值”);
paramMap.put(“userArea”,”对应具体的参数值”);
User user = xxx.selectUser(paramMap);
}

这种方法不够直观,看到接口方法不能直接的知道需要传递的参数有哪些?
3.使用@param注解
Dao层的函数方法

1
public User selectUser(@Param(“userName”)String name,@Param(“userArea”)String area);

对应的Mapper.xml文件

1
2
3
<select id="selectUser" resultMap="BaseResultMap">
select * from user_user where user_name = #{userName,jdbcType=VARCHAR}and user_area=#{userArea,jdbcType=VARCHAR}
</select>

这种方法最好,能让开发者看到dao层方法就知道该传什么样的参数,在xml中也相比其他两种方法清楚。

  • 作者: Sam
  • 发布时间: 2018-07-01 22:17:31
  • 最后更新: 2019-12-09 23:03:26
  • 文章链接: https://ydstudios.gitee.io/post/98398c3d.html
  • 版权声明: 本网所有文章除特别声明外, 禁止未经授权转载,违者依法追究相关法律责任!