[Detailed explanation] @Param annotation usage

1 Overview

      First of all, it is clear that this annotation is for parameter assignment in the SQL statement.

      The role of @Param is to name the parameters, such as a method A (int id) in the mapper, when an annotation is added, A (@Param("userId") int id), which means that the external wants to retrieve the passed id value , Just take its parameter name userId. Pass the parameter value as in the SQL statement, and assign the value to the SQL parameter through #{userId}.

2. Examples:

    Example 1: @Param annotates basic types of parameters

    Methods in mapper:

public User selectUser(@Param("userName") String name,@Param("password") String pwd);

  Map to the <select> tag in xml

<select id="selectUser" resultMap="User">  
   select * from user  where user_name = #{userName} and user_password=#{password}  
</select>

     Where user_name = #{userName} and user_password = #{password} the userName and password are all taken from the annotation @Param(), and the values ​​taken out are the values ​​of the formal parameters String name and String pwd in the method.

    Example 2: @Param annotation JavaBean object

   The SQL statement uses the alias in the @Param annotation to take out the attributes in the object and copy it

    Methods in mapper: 

public List<User> getAllUser(@Param("user") User u);

    Map to the <select> tag in xml

<select id="getAllUser" parameterType="com.vo.User" resultMap="userMapper">  
        select   
        from user t where 1=1  
             and   t.user_name = #{user.userName}  
              and   t.user_age = #{user.userAge}  
    </select>  

3, notes

   When the @Param annotation is used to declare parameters, the value of the SQL statement uses #{}, and the value of ${} can be used.

   When you do not use the @Param annotation to declare parameters, you must use #{} to take the parameters. If you use ${} to get a value, an error will be reported.

   When the @Param annotation is not used, there can be only one parameter, and it is a Javabean. JavaBean properties can be referenced in SQL statements, and only JavaBean properties can be referenced.
 

    @Select("SELECT * from Table where id = ${id}")
    Enchashment selectUserById(User user);

 

 

Guess you like

Origin blog.csdn.net/Sunshineoe/article/details/114697944