Most projects now use Mybatis, but some companies use Hibernate. The biggest feature of using Mybatis is that SQL needs to be written by itself, and writing SQL needs to pass multiple parameters. Passing parameters in complex business scenarios is also an art.

The following is a summary of several methods of multi-parameter passing.

Method 1: Sequential parameter transfer

public User selectUser(String name, int deptId);

<select id="selectUser" resultMap="UserResultMap">
    select * from user
    where user_name = #{0} and dept_id = #{1}
</select>
Copy the code

The numbers in #{} represent the order in which you pass the arguments.

This method is not recommended because the SQL layer is not intuitive and is prone to error once the order is adjusted.

Method 2: @param annotation method

public User selectUser(@Param("userName") String name, int @Param("deptId") deptId);

<select id="selectUser" resultMap="UserResultMap">
    select * from user
    where user_name = #{userName} and dept_id = #{deptId}
</select>
Copy the code

The name inside #{} corresponds to the name inside the parentheses of the @param annotation.

This method is more intuitive in the case of few parameters and is recommended.

Method 3: Map parameter transfer

public User selectUser(Map<String, Object> params);

<select id="selectUser" parameterType="java.util.Map" resultMap="UserResultMap">
    select * from user
    where user_name = #{userName} and dept_id = #{deptId}
</select>
Copy the code

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

This method is suitable for transferring multiple parameters, and the parameters are changeable and can be transferred flexibly.

Method 4: Java Bean parameter method

public User selectUser(Map<String, Object> params);

<select id="selectUser" parameterType="com.test.User" resultMap="UserResultMap">
    select * from user
    where user_name = #{userName} and dept_id = #{deptId}
</select>
Copy the code

The names in #{} correspond to member attributes in the User class.

This approach is straightforward, but you need to create an entity class, which is not easy to extend, and you need to add attributes, depending on the situation.

If you have gained, share your moments with more people!

Recommended reading


Resources: Ten stages of learning to become an architect!

Tutorials: The most powerful Spring Boot & Cloud tutorials ever

Tools: Recommended an online creation flow chart, mind mapping software

Scan and follow our wechat official account, reply “666” to get a set of Java concurrent programming HD video tutorial.