web123456

【Detailed explanation】Usage of @Param annotation

Welcome to follow the official account: Tiantian Shuo Programming. Your attention is my greatest motivation!

Free resume modification, information sharing, and interview experience sharing. Just send a private message.

1. Overview

First, make it clear that this annotation serves as parameter assignment in SQL statements.

The function of @Param is to name parameters. For example, in a certain method A (int id) in mapper, when adding annotation A (@Param("userId") int id), that is, if you want to retrieve the incoming id value from the outside, you only need to take its parameter name userId. Pass the parameter value as in a SQL statement, and assign the value to the SQL parameter through #{userId}.

2. Example:

Example 1: @Param annotation parameters of basic types

Methods in mapper:

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

Map to the <select> tag in xml

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

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

Example 2: @Param annotation of JavaBean objects

SQL statements take out the attributes in the object and copy them through the alias in the @Param annotation

Methods in mapper:

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

Map to the <select> tag in xml

<select  parameterType="" resultMap="userMapper">  
        select   
        from user t where 1=1  
             and   t.user_name = #{}  
              and   t.user_age = #{}  
    </select>  

3. Pay attention

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

When you do not use the @Param annotation to declare parameters, you must use #{} to get the parameters. Using ${} to get the value will cause an error.

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

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

If it helps you, thanks for your support! Your attention is my motivation to move forward!

Welcome to follow the official account: Tiantian Shuo Programming. Your attention is my greatest motivation!

Free resume modification, information sharing, and interview experience sharing. Just send a private message.