4 ways for Mybatis to pass multiple parameters

Reprinted from  Mybatis 4 ways to pass multiple parameters (dry goods)

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 requires passing multiple parameters. In the face of various complex business scenarios, passing parameters is also a kind of knowledge.

The following is a summary of the following methods for passing multiple parameters.

Method 1: Sequential parameter passing method

publicUser selectUser(String name,int deptId);<select id="selectUser" resultMap="UserResultMap">select*from userwhere user_name =#{0} and dept_id = #{1}
</select>  


      
     

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

This method is not recommended, the expression of the SQL layer is not intuitive, and it is easy to make mistakes once the order is adjusted.

Method 2: @Param annotation parameter transfer method

publicUser selectUser(@Param("userName")String name,int@Param("deptId") deptId);<select id="selectUser" resultMap="UserResultMap">select*from userwhere user_name =#{userName} and dept_id = #{deptId}
</select>    


      
     

  1. #{}The name inside corresponds to the name modified in the annotation @Parambrackets .

This method is relatively intuitive when there are not many parameters, and it is recommended to use it.

Method 3: Map parameter transfer method

publicUser selectUser(Map<String,Object>params);<select id="selectUser" parameterType="java.util.Map" resultMap="UserResultMap">select*from userwhere user_name =#{userName} and dept_id = #{deptId}
</select>   


      
     

#{}The name inside corresponds Mapto the key name inside.

This method is suitable for passing multiple parameters, and the parameters are volatile and can be passed flexibly.

Method 4: Java Bean parameter transfer method

public User selectUser(User params);

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

#{}里面的名称对应的是 User类里面的成员属性。

这种方法很直观,但需要建一个实体类,扩展不容易,需要加属性,看情况使用。


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324852736&siteId=291194637