46

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

 5 years ago
source link: https://www.ydstudio.net/archives/71.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

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

  1. 多个形参传递多参数

    Dao层的函数方法

public User selectUser(String name,String area);

对应的Mapper.xml文件

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

其中,#{0}代表接收的是dao层中的第一个参数,#{1}代表dao层中第二参数,更多参数以此类推即可。

  1. 采用Map传递多参数

    Dao层的函数方法

public User selectUser(Map paramMap);

对应的Mapper.xml文件

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

Service层调用

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

这种方法不够直观,看到接口方法不能直接的知道需要传递的参数有哪些?

  1. 使用@param注解

    Dao层的函数方法

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

对应的Mapper.xml文件

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

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

最后更新于 2018-07-01 22:28:43 并被添加「java mybatis」标签,已有 1 位童鞋阅读过。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK