1、MyBatis的参数映射配置

MyBatis的参数映射利用的属性是:parameterType。这个属性是可选的,因为 MyBatis 可以通过类型处理器(TypeHandler)推断出具体传入语句的参数。

2、简单类型,不需要设置 parameterType

对于大多数简单的使用场景,你都不需要使用复杂的参数,比如:

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

上面的这个示例说明了一个非常简单的命名参数映射。鉴于参数类型(parameterType)会被自动设置为 int,这个参数可以随意命名。

3、复杂类型,需要设置 parameterType

原始类型或简单数据类型(比如 Integer 和 String)因为没有其它属性,会用它们的值来作为参数,不需要设置 parameterType。 然而,如果传入一个复杂的对象,行为就会有点不一样了。比如:

<insert id="insertUser" parameterType="User">
  insert into users (id, username, password)
  values (#{id}, #{username}, #{password})
</insert>

此时需要 User 类型的参数对象传递到了语句中,会查找 id、username 和 password 属性,然后将它们的值传入预处理语句的参数中。

另外,还可以使用 map 传递,这是最原始的用法。定义接口使用map传递多个参数进行查询,如下所示:

public List<Product> getByMap(Map<String, Object> paramMap);

sql语句

<!--通过map传递参数 -->
<select id="selectUsers" resultType="User" parameterType="map">
  select id, username, password
  from users
  where id = #{id} and age = #{age}
</select>

需要注意的有:
1、parameterType参数类型为map(此处使用别名)
2、参数名称是map中的key

4、复杂类型,使用注解传递参数,不需要设置 parameterType

创建接口,使用注解传递多个参数进行查询

public List<Users> getUsers(@Param("name") String name, @Param("age") int age);
<select id="selectUsers" resultType="User">
  select id, username, password
  from users
  where id = #{id} and age = #{age}
</select>

这种方式不需要设置参数类型 ,参数名称为注解定义的名称。这种方式能够大大提高可读性,但是只适合参数较少的情况,一般是少于5个用此方法

5、小结

在不使用@Param注解的时候,函数的参数只能为一个,并且在查询语句取值时只能用#{}。如果想传递多个参数,parameterType参数类型为map(此处为别名)或者为JavaBean。

而使用@Param注解则可以使用多个参数,无需再设置parameterType,并且在查询语句中使用时可以使用#{}或者${}

标签: none

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


添加新评论