我们知道,从本质上来说,MyBatis就是一个映射器,它分为两部分映射:SQL语句映射和查询结果的映射。

在组装SQL语句的时候,往往需要各种参数,可以使用@param注解来映射参数,也可以使用XML的parameterType属性来映射参数,但最终都离不开XML语句中的SQL参数占位符。关于@param注解和parameterType属性的详细介绍,请移步这里,http://www.mybatis.cn/archives/920.html,不再赘述。本文主要讲一下SQL参数占位符的写法。

如果参数只有一个,并且为原始类型或简单数据类型(比如Integer和String,因为没有其它属性,会用它们的值来作为参数),此时参数可以随意命名。如下所示:

<select id="selectUsers" resultType="User">
  select id, username, password
  from users
  where id = #{id}
</select>

但是,当有多个参数的时候,SQL参数占位符该如何写,则需要关注useActualParamName属性的设置。

useActualParamName的作用

useActualParamName的作用:允许使用方法签名中的名称作为语句参数名称。从3.4.1版本开始,MyBatis的全局配置useActualParamName默认为true。当然,我们也可以设置为false,如下所示:

<setting name="useActualParamName" value="false" />

备注:MyBatis的xml配置文件中声明settings属性的useActualParamName参数值为true。

useActualParamName的属性值与SQL参数占位符的关系

useActualParamName的属性值与SQL参数占位符有什么关系呢?请看下面的例子介绍:

public interface UserDao 
{
    User findUserById(int id, String name);
}

如果useActualParamName设置为true时,则传递参数需要使用

#{arg0}-#{argn}或者#{param1}-#{paramn}

比如:

<select id="findUserById" resultType="cn.mybatis.entity.User" >
  select * from t_users where id = #{arg0}  and name =#{arg1}
</select>

或者

<select id="findUserById" resultType="cn.mybatis.entity.User" >
  select * from t_users where id = #{param1}  and name =#{param2}
</select>

如果useActualParamName设置为false时,则传递参数需要使用

#{0}-#{n}或者#{param1}-#{paramn}

比如:

<select id="findUserById" resultType="cn.mybatis.entity.User" >
  select * from t_users where id = #{0}  and name =#{1}
</select>

或者

<select id="findUserById" resultType="cn.mybatis.entity.User" >
  select * from t_users where id = #{param1}  and name =#{param2}
</select>

下面的写法是错误的,因为直接写参数名:

<select id="findUserById" resultType="cn.mybatis.entity.User" >
  select * from t_users where id = #{id}  and name =#{name}
</select>

这个时候要注意参数的设置问题了。另外还有个特例:如果方法只有一个参数是可以用参数名代替的,其实如果只有一个参数,任何名称都是可以的。

标签: none

[网站公告]-[2024年兼职介绍]


添加新评论