MyBatis 参数

MyBatis参数

前提

本文中所有的Java Mapper方法参数都是未使用@Param参数声明参数的即Mybatis默认处理参数。

MyBatis参数访问常见错误及解决

以下错误都是MyBatis访问时变量名称与默认参数名称不一致时导致的。

  • Error querying database. Cause: org.apache.ibatis.binding.BindingException: Parameter ‘xxx’ not found. Available parameters are [arg0, collection, list]
    单个Collection参数且未通过@Param注解指定名称时报该错误,可以在XML映射文件中将xxx改arg0或collection或list都可以,还可以再Java Mapper参数前添加注解@Param(“xxx”)解决。

  • Error querying database. Cause: org.apache.ibatis.binding.BindingException: Parameter ‘xxx’ not found. Available parameters are [arg1, arg0, param1, param2]
    多个参数且未通过@Param(“xxx”)注解指定名称时报该错误,通过@Param(“xxx”)注解指定名称,或者改为单个Map解决。

默认参数访问

单个参数

单个基本类型

Java Mapper

User queryById(Long id);

Xml Mapper

<select id="queryById" resultType="io.github.jast90.mybatis.param.User">
        select id,`name`,`password` from `user`
        where id=#{ids} # 任意名称都可以
select>

基本不会报错

单个Collection类型

Java Mapper

List<User> queryByIds(List<Long> ids);

Xml Mapper

<select id="queryByIds" resultType="io.github.jast90.mybatis.param.User">
        select id,`name`,`password` from `user`
        where id in
        <foreach collection="ids" item="item" open="(" close=")" separator=",">
            #{item}
        foreach>
    select>

会报Error querying database. Cause: org.apache.ibatis.binding.BindingException: Parameter ‘xxx’ not found. Available parameters are [arg0, collection, list] 错误,参考常见错误解决

单个Map类型

Java Mapper

User queryByNameAndPasswordByMap(Map<String,String> param);

Xml Mapper

<select id="queryByNameAndPasswordByMap" resultType="io.github.jast90.mybatis.param.User">
        select id,`name`,`password` from `user`
        where `name`=#{name} and `password`=#{password} 
select>

xml中接通过map的key就可以访问。

单个参数访问小结
  • 单个基本参数时,XML默认访问参数名称可以是随意字符串
  • 单个Collection参数时,XML默认访问参数名称可以是arg0, collection, list中任意
  • 单个Map参数时,XML默认访问参数名称是Map的key

多个参数

无论时多个基本类型,多个Collection类型,多个Map类型,多个基本类型、Collection类型、Map类型默认都只能通过arg[0…n-1]或param[1…n]来访问

多个参数小结
  • arg以0开始
  • param以1开始
  • argi或者parani是Map时XML映射文件中可以通过.key获取Map的key值

@Param参数访问

可以通过@Param注解指定XML中访问的参数名,XML中与@Param("name")中的name一致就可以访问到,注意是Mybatis的@Param的注解。

你可能感兴趣的:(mybatis)