What is the method of passing multiple parameters in MyBatis?
In MyBatis, there are multiple ways to pass multiple parameters.
- By using either the Map annotation or @Param annotation, you can place multiple parameters into a single Map or assign a name to each parameter using @Param, allowing you to reference the parameters by name in the SQL statement.
For example, passing multiple parameters using a Map:
Map<String, Object> params = new HashMap<>();
params.put("param1", value1);
params.put("param2", value2);
List<ResultType> result = sqlSession.selectList("namespace.statement", params);
Alternatively, use the @Param annotation to pass multiple parameters.
List<ResultType> result = sqlSession.selectList("namespace.statement", @Param("param1") value1, @Param("param2") value2);
In SQL statements, parameters can be referenced using ${param1} and ${param2}.
- Using POJO objects: multiple parameters can be encapsulated into a single POJO object, and the attributes of the POJO can be directly referenced in SQL statements.
For example, define a POJO (Plain Old Java Object) class:
public class MyParams {
private String param1;
private String param2;
// getters and setters
}
Then reference the properties of the POJO in the SQL statement.
<select id="statement" parameterType="com.example.MyParams" resultType="com.example.ResultType">
SELECT * FROM table WHERE column1 = #{param1} AND column2 = #{param2}
</select>
When making a call, pass multiple parameters encapsulated in a POJO object.
MyParams params = new MyParams();
params.setParam1(value1);
params.setParam2(value2);
List<ResultType> result = sqlSession.selectList("namespace.statement", params);
These methods all allow for passing multiple parameters, simply choose the method that is most suitable for your specific scenario.