SoFunction
Updated on 2025-03-08

Four ways MyBatis pass parameters in mapper

Preface

In MyBatis file, the following methods can be used to pass parameters:

1. Positional parameters

Use in SQL statements${1}${2}The equivalent placeholder represents the position of the parameter, and then pass the parameter through the position of the parameter in the method. For example:

public User queryUser(String name, int age);
<select  resultType="User">
  SELECT * FROM users WHERE  name = ${1} AND dept_id = ${2}
</select>

When calling this query method in Java code, you need to pass parameters of String and int type, and the numbers in #{} represent the order of incoming parameters.

2. Named parameters

Use in SQL statements#{paramName}to represent named parameters, and then add to the parameters in the method@ParamAnnotation to pass parameters. For example:

public User queryUser(@Param("name") String name, int @Param("age") age);
<select  resultType="User">
  SELECT * FROM users WHERE name = #{name} AND age = #{age}
</select>

When calling this query method in Java code, you need to pass parameters of String and int type, which will be replaced at #{name} and #{age} in the SQL statement. At the same time, add @Param("name") and @Param("age") annotations to the method's parameter list, and the name of the specified parameter matches the named parameters in the SQL statement.

3. Object parameters

If the passed parameter is an object, you can directly use the object's properties to reference the parameters in the SQL statement. For example:

public User queryUser(User user);
<select  parameterType="" resultType="User">
  SELECT * FROM users WHERE name = #{name} AND age = #{age}
</select>

When calling this query method in Java code, you need to pass a User object as a parameter, which containsnameandageproperty. These two properties will be replaced by the SQL statement respectively.#{name}and#{age}place.

4. Map parameters

Parameters can be encapsulated into a map and passed as parameters of the mapper method.

public User queryUser(Map<String, Object> params);
<select  parameterType="" resultType="User">
  SELECT * FROM users WHERE name = #{name} AND age = #{age}
</select>

The name in #{} corresponds to the key name in the Map.

No matter which way you pass the parameters, you need to define the corresponding method in the mapper interface and add the correct parameter type and parameter name to the method's parameter list to match the SQL statement in the file. MyBatis will automatically pass parameters in the method to the corresponding location or named parameters of the SQL statement.

This is the article about the four ways MyBatis pass parameters in mapper. For more related content of MyBatis mapper, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!