天天看點

@Param在Mybatis中的使用

用注解來簡化xml配置的時候,@Param注解的作用是給參數命名,參數命名後就能根據名字得到參數值,正确的将參數傳入sql語句中

1.如果mapper接口裡參數是兩個普通參數;如下圖

public List<student> selectuser(int pn ,String i);
           
<select id="selectuser"  resultType="com.user.entity.student">
        SELECT * FROM student
         where sname like concat(concat("%",#{1}),"%")
         LIMIT #{0} ,5    
</select>
           

那麼xml裡隻能用#{0},#{1}的方式,但這樣的表達方法,不利于後期的維護。 可以用@Param的注解來修飾參數。xml裡看起來也比較友善,否則一堆0,1,2,3的真是難懂。

public List<student> selectuser(@Param(value = "page")int pn ,@Param(value = "str")String i);
           
<select id="selectuser"  resultType="com.user.entity.student">
    SELECT * FROM student
    where sname like concat(concat("%",#{str}),"%")
    LIMIT #{page} ,5
</select>
           

2,如果傳入的參數是基本類型參數和實體類對象。

public List<student> selectuser(@Param(value = "page")int pn ,@Param(value = "st")student student);
           
<select id="selectuser"  resultType="com.user.entity.student">
    SELECT * FROM student
    where sname like concat(concat("%",#{st.sname}),"%")
    LIMIT #{page} ,5
</select>
           

3.如果傳入的參數隻有一個,基本上不用@Param這個注解了。正常用

public List<student> selectuser(int pn);
           
<select id="selectuser"  resultType="com.user.entity.student">
        SELECT * FROM student
        <!--where sname like concat(concat("%",#{st.sname}),"%")-->
        LIMIT #{page} ,5
</select>