Using @Param Annotation for Mapper Method Parameters in MyBatis
The @Param annotation is used before a method parameter of a Mapper interface to specify the name of the parameter used by a SQL statement in a Mapper mapping file.
For example, consider a Mapper interface with the following method:
public User selectUserByName(String name);
And a corresponding Mapper mapping file with the following SQL statement:
<select id="selectUserByName" resultType="User">
SELECT * FROM users WHERE name = #{name}
</select>
Here, the #{name} placeholder in the SQL statement refers to the parameter named 'name' passed to the selectUserByName method. The @Param annotation is used to explicitly specify the parameter name, ensuring that the MyBatis framework correctly maps the method parameter to the SQL statement.
Without the @Param annotation, MyBatis would use the parameter name from the method signature, which might not align with the placeholder name in the SQL statement. The @Param annotation helps to avoid this potential conflict and ensure proper parameter mapping.
Here's how you would use @Param in the Mapper interface:
public User selectUserByName(@Param("name") String name);
By using the @Param("name") annotation, you explicitly specify the name of the method parameter as 'name', ensuring it matches the placeholder in the SQL statement. This practice improves code clarity and maintainability, especially when working with complex Mapper interfaces and SQL statements.
原文地址: https://www.cveoy.top/t/topic/oCFT 著作权归作者所有。请勿转载和采集!