How does MyBatis accept map parameters?

In MyBatis, you can receive Map type parameters using the @Param annotation and the #{} placeholder.

Firstly, use the #{key} placeholder in the SQL statement to reference the value in the Map. For example:

<select id="selectUser" resultType="User">
  SELECT * FROM user WHERE id = #{id} AND name = #{name}
</select>

Next, use the @Param annotation in the method parameters to identify parameters of type Map and use the keys from the Map in the #{} placeholders. For example:

@Select("SELECT * FROM user WHERE id = #{id} AND name = #{name}")
User selectUser(@Param("id") int id, @Param("name") String name);

If the parameter is a complex Map object, you can specify the parameter name using the @Param annotation, and then reference the values in the Map using #{paramName.key} in the SQL statement. For example:

@Select("SELECT * FROM user WHERE id = #{param.mapKey} AND name = #{param.mapValue}")
User selectUser(@Param("param") Map<String, Object> paramMap);

When calling a method, you can pass a Map parameter that includes key-value pairs. For example:

Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", 1);
paramMap.put("name", "Alice");

User user = userDao.selectUser(paramMap);

Please be aware that when using the @Param annotation in XML configuration files, you need to set useActualParamName to true so that MyBatis can correctly parse the parameter names. For example:

<settings>
  <setting name="useActualParamName" value="true" />
</settings>
广告
Closing in 10 seconds
bannerAds