记录折腾的那点事
在折腾的道路上永不止步

mybatis中传入多个参数的4个解决方法

mybatis中传入多个参数的4个解决方法

问题引入

想必大家可能遇到过类似的错误,当传入多个参数时,映射文件无法获得传入的参数
这里写图片描述
我的例子

// javabeanpublic class User { private int id; private String name; private byte age; // 忽略了getter、setter方法}// 接口public interface UserMapper {    List<User> select(String name,byte age);}// 映射文件<select id="select" resultType="model.User"> select * from `user` where name = #{id} and age =#{age}</select>

1. 利用参数出现的顺序

Parameter ‘id’ not found. Available parameters are [arg1, arg0, param1, param2],这句话的意思就是id找不到,可用的参数是[arg1, arg0, param1, param2]。所以可使用参数出现的顺序号码引用参数,第一个参数用arg0或param1表示,第二个参数用arg1或param2表示,以此类推(arg从0开始计数,param从1开始计数)。

修改xml为如下方式:
<select id="select" resultType="model.User"> select * from `user` where name = #{arg0} and age =#{arg1}</select>// or<select id="select" resultType="model.User"> select * from `user` where name = #{param1} and age =#{param2}</select>

2.使用注解

给接口中方法的参数加上注解,xml不变
public interface UserMapper {    List<User> select(@Param("name") String name,@Param("age") byte age);}

3.使用map

3.1把接口的形参改为Map

// 接口public interface UserMapper {    List<User> select(Map params);}

3.2 把需要的参数封装在map中

Map params = new HashMap();params.put("name", "王尼玛");params.put("age", 32);List<User> list = userMapper.select(params);

4.把参数封装在Javabean中

4.1 把接口的形参改为javabean

// 接口public interface UserMapper {    List<User> select(User user);}

4.2 把需要的参数封装在javabean中

User user = new User();user.setName("四");user.setAge((byte)43);List<User> list = userMapper.select(user);

so,我觉得应该把题目改为,mybatis中传入多个参数的2个解决方法。毕竟3、4是通过把多个参数转化为1个参数的方式解决问题的,哈哈。


5 拓展(接口中传入参数的各种情况)

5.1 当只有一个参数时

使用arg0,param1获得参数是一直有效的,但是个人不推荐这样做,毕竟看起来不优雅

5.1.1 参数是基本类型

xml中标签内的变量名可以随便写,#{id},#{ids},#{123},#{xxgdsgdg},等都可以获得到参数。

5.1.2 参数是javabean

xml中标签内直接填写Javabean中的属性名

5.1.3 参数是数组

使用array获得参数,再用foreach循环

5.1.4 参数是List

使用list或collection获得参数,再用foreach循环

5.1.5 参数是Set

使用collection获得参数,再用foreach循环

5.2 当有多个参数时

使用argN、paramN或@param定位到某个参数,再灵活使用ognl就ok了。比如#{user.name}、#{users[0].name}。
赞(0)
未经允许不得转载:ghMa » mybatis中传入多个参数的4个解决方法
分享到: 更多 (0)

评论 1

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #1

    mybatis多个参数:
    1. 注解(最常用)
    2. 转化为对象或MAP
    3. 按顺序(这个最蠢,写的代码看得费劲)
    单个参数需要注意得:
    1.基本数据类型随便写
    2.数组用array,list/set用collection 进行foreach

    tt4年前 (2020-06-02)回复