Passing Multiple Parameters in MyBatis
In MyBatis, there are typically two ways to pass in multiple parameter types:
- Encapsulate multiple parameters using a Map: bundle multiple parameters into a Map and pass the Map as a parameter to the Mapper method. Within the Mapper method, you can retrieve the corresponding parameter value by specifying the key.
public interface UserMapper {
List<User> selectUsersByCondition(Map<String, Object> params);
}
In the Mapper XML file, you can retrieve parameter values using the syntax ${key}.
<select id="selectUsersByCondition" parameterType="map" resultType="User">
SELECT * FROM user
WHERE name = #{name} AND age = #{age}
</select>
Then, when calling the Mapper method, pass in a Map containing multiple parameters.
Map<String, Object> params = new HashMap<>();
params.put("name", "Alice");
params.put("age", 18);
List<User> users = userMapper.selectUsersByCondition(params);
- Specify parameter names using the @Param annotation: In the Mapper method, use the @Param annotation to assign a name to each parameter, and then use the specified parameter name in the Mapper XML file to retrieve the parameter values.
public interface UserMapper {
List<User> selectUsersByCondition(@Param("name") String name, @Param("age") int age);
}
In the Mapper XML file, you can access parameter values using #{parameterName}.
<select id="selectUsersByCondition" resultType="User">
SELECT * FROM user
WHERE name = #{name} AND age = #{age}
</select>
Then, when calling the Mapper method, pass in multiple parameters and specify their names.
List<User> users = userMapper.selectUsersByCondition("Alice", 18);
The above are two common ways to pass multiple parameter types into MyBatis. The choice between the two methods depends on personal preference and project requirements.