Usage of @ Param annotation based on dao interface in ssm

  • 2021-08-16 23:59:29
  • OfStack

Use of @ Param annotation: Conditional parameter binding in sql statement in xml file for the shape of method in interface

1. The interface method has only one parameter

There is no need to use @ Param annotation at all

Example:


public interface PaperDao {
  Paper queryById(long id);
} 

At this time, in the corresponding xml file, you can fill in any name in # {}


 
<select id="queryById" parameterType="long" resultMap="resultMap1">
  SELECT paper_id,name,number,detail
  FROM paper
  WHERE paper_id=#{id}
</select>

2. Interface methods have multiple parameters

The @ Param annotation is recommended for parameter binding

Example:


public interface PaperDao {
  Paper queryById(@Param("id") long id , @Param("name") String name);}

xm file:


<select id="queryById" parameterType="long" resultMap="resultMap1">
  SELECT paper_id,name,number,detail
  FROM paper
  WHERE paper_id=#{id} AND name=#{name}
</select>

Added: A few details about the use of @ Param annotations in the SSM integration process

1. First of all, declare the function of this annotation under 1, which is to name the parameters to find the corresponding parameters.

For example (for example, in the XXXMapper. xml file of Mybatis, aiming at an sql statement, such as querying an entity according to id, if the parameter column we passed in is named id, but the column of the entity class is indeed userID, then we can name the parameter line userID.

At this time, we can find the parameter according to this name, which is similar to the feeling of one "id" of the parameter, so that the parameter can be correctly injected into the sql statement.

For example:


public int getUserDetail(@Param("userId") int id);
// Here we can use #{userId} To get the id Value of   In execution sql Statement time 

Another advantage is that when using this annotation to declare parameters, using # {} and KaTeX parse error: Expected 'EOF', got '#' at position 25: … will report an error, but if you don't use it, you can only use # {} (1 in most cases, # {}, … ${} will cause sql injection problems.

But here I sum up a very bad problem I encountered when I used this annotation, that is, when you call a function with @ Param annotation, you will report an error when passing parameters, which needs attention


Related articles: