How to pass multiple parameters in MyBatis?

There are several ways to pass multiple parameters in MyBatis.

  1. Using a Map as a parameter: multiple parameters can be encapsulated into a Map, which is then passed as a parameter to MyBatis’ SQL statements. The corresponding parameter values can be accessed in the SQL statements using the key.

For example, create a Map and assign multiple parameters to it.

Map<String, Object> params = new HashMap<>();
params.put("param1", value1);
params.put("param2", value2);

Then, retrieve the parameter value through key in the SQL statement of MyBatis.

<select id="selectByExample" parameterType="java.util.Map" resultMap="BaseResultMap">
    SELECT * FROM your_table WHERE column1 = #{param1} AND column2 = #{param2}
</select>
  1. By using the @Param annotation, you can specify a name for each parameter and pass multiple parameters in order to the SQL statement in MyBatis. The parameter values can then be retrieved in the SQL statement using the specified names.

For example, define a method and specify parameter names using the @Param annotation.

@Select("SELECT * FROM your_table WHERE column1 = #{param1} AND column2 = #{param2}")
List<YourEntity> selectByParams(@Param("param1") Object param1, @Param("param2") Object param2);
  1. Using JavaBean as a parameter: you can encapsulate multiple parameters into a single JavaBean, then pass the JavaBean as a parameter to MyBatis SQL statements. Within the SQL statement, you can retrieve the corresponding parameter values by using the JavaBean’s property name.

For example, define a JavaBean and set multiple parameters.

public class MyBean {
    private Object param1;
    private Object param2;
    // getter and setter
}

MyBean bean = new MyBean();
bean.setParam1(value1);
bean.setParam2(value2);

Then, in the SQL statement of MyBatis, retrieve the parameter value using the JavaBean’s property name.

<select id="selectByBean" parameterType="your.package.MyBean" resultMap="BaseResultMap">
    SELECT * FROM your_table WHERE column1 = #{param1} AND column2 = #{param2}
</select>

Here are some common ways to pass multiple parameters, choose the most suitable method based on the actual situation.

bannerAds