MyBatis可以通過兩種方式接收多個參數:
public interface MyMapper {
List<User> getUsers(@Param("name") String name, @Param("age") int age);
}
<select id="getUsers" resultType="User">
SELECT * FROM users
WHERE name = #{name}
AND age = #{age}
</select>
public interface MyMapper {
List<User> getUsers(Map<String, Object> params);
}
<select id="getUsers" resultType="User">
SELECT * FROM users
WHERE name = #{name}
AND age = #{age}
</select>
使用示例:
Map<String, Object> params = new HashMap<>();
params.put("name", "John");
params.put("age", 30);
List<User> users = myMapper.getUsers(params);
或者:
public class UserParams {
private String name;
private int age;
// getters and setters
}
UserParams params = new UserParams();
params.setName("John");
params.setAge(30);
List<User> users = myMapper.getUsers(params);
無論使用哪種方式,MyBatis都會根據參數的名稱或者屬性名來匹配SQL語句中的參數。