简述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>

今天有点累,写的过程若有笔误或错误,请私信联系

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