簡述mybatis的四種傳入多個參數的方法

使用mybatis在CRUD的時候經常會需要傳入參數,在語法上,mybatis只允許傳入一個參數,但是通過一些技巧,我們就可以傳入多個參數,下面我簡述傳入多個參數的四種方法。

第一種方法 邏輯擴充

我們最常用的方法就是使用邏輯擴充方法。
模擬場景:我們需要添加學生的三個屬性值到數據庫內,分別爲studentId,studentName,studentAge,此時可以將三個屬性封裝成Student對象,邏輯上將三個值合併成一個對象,然後如下代碼:

   <!--
        parameterType   填入封裝對象的那個類的完整路徑
        id              接口的方法名
        #{}             用於獲取對象對應的屬性值
    
    -->
  <insert id="addStudent" parameterType="com.example.model.Student">
        insert into student(studentId,studentName,studentAge) values (#{studentId},#{studentName},#{studentAge})
  </insert>

第二種方法 在接口方法中傳入多個參數

我們只需要在接口方法中傳入多個參數,不過在mapper中我們需要注意:
1.省略parameterType屬性
2.使用param1,param2……或是arg0,arg1……代替參數來使用
具體使用看下面代碼:

接口 StudentMapper.java
/**
	這裏建議
		1.雖然是添加學生,照理來說不需要返回值,但是我們還是寫了一個Integer型的返回值,
		  此時返回的是影響的行數。用於檢測插入數據到數據庫是否成功
		2.參數內使用Integer而非int是因爲防止int型默認爲0
*/
public interface StudentMapper {
    public Integer addStudent(Integer studentId,String studentName,Integer studentAge);
}
配置 StudentMapper.xml
   <!--
        id              接口的方法名
        #{}             用於獲取對象對應的屬性值
    -->
  <insert id="addStudent">
        insert into student(studentId,studentName,studentAge) values (#{param1},#{param2},#{param3})
  </insert>

  <!--或者這麼寫-->
    <insert id="addStudent">
        insert into student(studentId,studentName,studentAge) values (#{arg0},#{arg1},#{arg2})
  </insert>

第三種方法 升級版

第二種方法顯而易見,十分的不方便。因爲光從sql語句中看,根本不知道自己傳入的(agr0,arg1……)是什麼東西。第三種是第二種方法的升級版,解決了參數不明確的問題。
第三種方法採用在接口中加入@Param()註釋爲參數設置別名的方式,下面是代碼:

接口 StudentMapper.java
public interface StudentMapper {
    public Integer addStudent(@Param("sId") Integer studentId, @Param("sName")String studentName, @Param("sAge")Integer studentAge);
}
配置 StudentMapper.xml
  <insert id="addStudent">
        insert into student(studentId,studentName,studentAge) values (#{sId},#{sName},#{sAge})
  </insert>

第四種方法 混合模式

情景:當你需要傳入的參數不僅有基本類型數據,還有對象時,可以結合第一第三種方法,如下使用

接口 StudentMapper.java
public interface StudentMapper {
	/**
		這裏Course是一個類,封裝了Course這個對象,有courseId,courseName兩個屬性
	*/
    public Integer addStudent(@Param("sCourse") Course course,@Param("sId") Integer studentId, @Param("sName")String studentName, @Param("sAge")Integer studentAge);
}
配置 StudentMapper.xml
  <insert id="addStudent">
        insert into student(studentId,studentName,studentAge,studentCourseId,studentCourseName) values (#{sId},#{sName},#{sAge},#{sCourse.courseId},#{sCourse.courseName})
  </insert>

今天有點累,寫的過程若有筆誤或錯誤,請私信聯繫

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章