Hibernate / MyBatis Interview questions
What is the @Param annotation used for in MyBatis?
The @Param annotation assigns an explicit name to a Mapper interface method parameter, which is needed whenever a statement takes more than one simple parameter, since #{} placeholders in the SQL need to reference each parameter by a name that Java doesn't otherwise preserve at runtime by default.
public interface UserMapper { User selectUserByNameAndStatus(@Param("name") String name, @Param("status") String status); }
<select id="selectUserByNameAndStatus" resultType="User"> SELECT * FROM users WHERE name = #{name} AND status = #{status} </select>
Without @Param, a method with a single parameter can still be referenced in #{} using any name as a loose convention, but a method with multiple simple parameters has no reliable way for MyBatis to know which Java argument corresponds to which named placeholder in the SQL, since standard Java bytecode doesn't retain parameter names unless the code is specifically compiled with debug information or the -parameters flag enabled.
An alternative to @Param for multiple parameters is bundling them into a single object or Map parameter instead, referencing fields or map keys directly in #{}; @Param is generally preferred for a small, fixed number of parameters since it keeps the method signature self-documenting, while an object/Map parameter tends to be preferred when the parameter set is large or needs to grow over time without repeatedly changing the method signature.
More Related questions...