mybatis中必須使用@param注解的四種情況


一、方法有多個參數

例如:

接口方法:

@Mapper
public interface UserMapper {
    Integer insert(@Param("username") String username, @Param("address") String address);
}

對應的xml:

<insert id="insert" parameterType="org.javaboy.helloboot.bean.User">
    insert into user (username,address) values (#{username},#{address});
</insert>

原因:當不使用 @Param 注解時,mybatis 是不認識哪個參數叫什么名字的,盡管在接口中定義了參數的名稱,mybatis仍然不認識。這時mybatis將會以接口中參數定義的順序和SQL語句中的表達式進行映射,這是默認的。

 

二、方法參數要取別名

例如

@Mapper
public interface UserMapper {
    Integer insert(@Param("username") String username, @Param("address") String address);
}

對應的xml:

<insert id="insert" parameterType="org.javaboy.helloboot.bean.User">
    insert into user (username,address) values (#{username},#{address});
</insert>

 

三、XML 中的 SQL 使用了 $ 拼接sql

$ 會有注入的問題,但是有的時候不得不使用 $ 符號,例如要傳入列名或者表名的時候,這個時候必須要添加 @Param 注解

例如:

@Mapper
public interface UserMapper {
    List<User> getAllUsers(@Param("order_by")String order_by);
}

對應xml:

<select id="getAllUsers" resultType="org.javaboy.helloboot.bean.User">
    select * from user
    <if test="order_by!=null and order_by!=''">
        order by ${order_by} desc
    </if>
</select>

 

四、動態 SQL 中使用了參數作為變量

如果在動態 SQL 中使用參數作為變量,那么也需要 @Param 注解,即使你只有一個參數。例如如下方法:

@Mapper
public interface UserMapper {
    List<User> getUserById(@Param("id")Integer id);
}

對應xml:

<select id="getUserById" resultType="org.javaboy.helloboot.bean.User">
    select * from user
    <if test="id!=null">
        where id=#{id}
    </if>
</select>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM