mybatis 傳遞參數的7種方法

在實際開發過程中,增刪改查操作都要涉及到請求參數的傳遞,今天這節就集中講下在mybatis中傳遞參數的7中方法

單個參數的傳遞很簡單沒有什麼好將的,這裏主要說下多個參數的傳遞

項目地址

1.第一種方式 匿名參數 順序傳遞參數

controller

@ApiOperation(value = "多個參數查詢_匿名順序傳參")
@GetMapping("findByParams")
public ResultMsg findByParams(Short gender,String age)
{
    List result= employeeMapper.selectByGenderAndAge(gender,age);
    return ResultMsg.getMsg(result);
}

mapper

List<Employee> selectByGenderAndAge(Short gender,String age );

xml

<select id="selectByGenderAndAge" resultMap="BaseResultMap" >
  select * from employee where gender = #{gender} and age = #{age}
</select>

注意這裏按參數名去引用的話會報如下錯誤,mybatis錯誤提示很細緻,這裏明確給我們提示,匿名參數只能使用

arg1, arg0, param1, param2 類似的形式

這種傳參方式的缺點是不夠靈活,必須嚴格按照參數順序來引用

BindingException: Parameter 'gender' not found. Available parameters are [arg1, arg0, param1, param2]

所以正確的引用方式如下:

  <select id="selectByGenderAndAge" resultMap="BaseResultMap" >
    select *  from employee where gender = #{param1} and age = #{param2}
  </select>

2.第二種方式 使用@Param註解

controller

@ApiOperation(value = "多個參數查詢_註解方式傳參")
@GetMapping("findByParams2")
public ResultMsg findByParams2(Short gender,String age)
{
    List result= employeeMapper.selectByGenderAndAge2(gender,age);
    return ResultMsg.getMsg(result);
}

mapper

使用@Param註解顯示的告訴mybatis參數的名字,這樣在xml中就可以按照參數名去引用了

List<Employee> selectByGenderAndAge( @Param("gender") Short gender,@Param("age") String age );

xml

<select id="selectByGenderAndAge" resultMap="BaseResultMap" >
  select * from employee where gender = #{gender} and age = #{age}
</select>

3.使用Map傳遞參數

實際開發中使用map來傳遞多個參數是一種推薦的方式

controller

@ApiOperation(value = "多個參數查詢")
@GetMapping("findByMapParams")
public ResultMsg findByMapParams(Short gender,String age)
{
    Map params = new HashMap<>();
    params.put("gender",gender);
    params.put("age",age);
    List result= employeeMapper.selectByMapParams(params);
    return ResultMsg.getMsg(result);
}

mapper

List<Employee> selectByMapParams(Map params);

可以看到使用map來傳遞多個參數,可以直接使用參數名稱進行引用

<select id="selectByMapParams" resultMap="BaseResultMap" parameterType="map">
  select * from employee where gender = #{gender} and age = #{age}
</select>

4.用過java bean傳遞多個參數

也可以使用bean的方式來傳遞多個參數,使用時parameterType指定爲對應的bean類型即可

這就傳參方式的優點是比較方便,controller層使用@RequestBody接收到實體類參數後,直接傳遞給mapper層調用即可,不需要在進行參數的轉換

controller

@ApiOperation(value = "多個參數查詢_通過Java Bean傳遞多個參數")
@PostMapping("findByBeans")
public ResultMsg findByBeans(@RequestBody Employee employee)
{
    List result= employeeMapper.selectByBeans(employee);
    return ResultMsg.getMsg(result);
}

mapper

List <Employee> selectByBeans(Employee employee);

xml

參數的引用直接使用bean的字段

<select id="selectByBeans" resultMap="BaseResultMap" parameterType="com.wg.demo.po.Employee">
  select
  *
  from employee where gender = #{gender} and age = #{age}
</select>

測試一下:

[外鏈圖片轉存失敗(img-J0AJRKOW-1562379805361)(http://i66.tinypic.com/iglo39.png)]

5.直接使用JSON傳遞參數

這也是推薦的一種傳參方式,controller層收到JSON型數據後,直接傳遞給mapper層進行查詢操作,簡單 方便

controller

@ApiOperation(value = "多個參數查詢_通過JSON傳遞多個參數")
@PostMapping("findByJSONObject")
public ResultMsg findByJSONObject(@RequestBody JSONObject params)
{
    List result= employeeMapper.findByJSONObject(params);
    return ResultMsg.getMsg(result);
}

mapper

List <Employee> findByJSONObject(JSONObject params);
<select id="findByJSONObject" resultMap="BaseResultMap" parameterType="com.alibaba.fastjson.JSONObject">
  select
  *
  from employee where gender = #{gender} and age = #{age}
</select>

測試一下:

[外鏈圖片轉存失敗(img-mL2LI1uF-1562379805363)(http://i68.tinypic.com/33x8zyv.png)]

6.傳遞集合類型參數List、Set、Array

在一些複雜的查詢中(如 sql中的 in操作),傳統的參數傳遞已無法滿足需求,這時候就要用到List、Set、Array類型的參數傳遞,具體使用如下:

controller

@ApiOperation(value = "多個參數查詢_通過List、Set、Array傳遞多個參數")
@PostMapping("findByList")
public ResultMsg findByList(@RequestBody List<String> list)
{
    List result= employeeMapper.findByList (list);
    return ResultMsg.getMsg(result);
}

mapper

List <Employee> findByList(List list);

xml

  <select id="findByList" resultMap="BaseResultMap" >
SELECT * from employee where age in
    <foreach collection="list" open="(" separator="," close=")" item="age">
      #{age}
    </foreach>
  </select>

這裏foreach表示循環操作,具體的參數含義如下:

foreach元素的屬性主要有 item,index,collection,open,separator,close。
item表示集合中每一個元素進行迭代時的別名,
index指定一個名字,用於表示在迭代過程中,每次迭代到的位置,
open表示該語句以什麼開始,
separator表示在每次進行迭代之間以什麼符號作爲分隔符,

close表示以什麼結束

在使用foreach的時候最關鍵的也是最容易出錯的就是collection屬性,該屬性是必須指定的,但是在不同情況下,該屬性的值是不一樣的,主要有一下3種情況:

  • 1.如果傳入的是單參數且參數類型是一個List的時候,collection屬性值爲list
  • 2.如果傳入的是單參數且參數類型是一個array數組的時候,collection的屬性值爲array
  • 3.如果傳入的參數是多個的時候,我們就需要把它們封裝成一個Map或者Object

測試:

[外鏈圖片轉存失敗(img-7YhlK1ip-1562379805364)(http://i64.tinypic.com/2rr14et.png)]

7.參數類型爲對象+集合

該類參數與java Bean參數形式類似,只不過更復雜一些,如下面的Department類,除了基本字段還包括一個Employee的列表

bean

@Data
public class Department {
    private Long id;

    private String deptName;

    private String descr;

    private Date createTime;

    List<Employee> employees;

}

controller

@ApiOperation(value = "多個參數查詢_對象+集合參數")
@PostMapping("findByDepartment")
public ResultMsg findByDepartment(@RequestBody Department department)
{
    List result= employeeMapper.findByDepartment(department);
    return ResultMsg.getMsg(result);
}

mapper

List <Employee> findByDepartment(@Param("department")Department department);

xml

<select id="findByDepartment" resultMap="BaseResultMap" parameterType="com.wg.demo.po.Department">
    SELECT * from employee where dept_id =#{department.id} and age in
    <foreach collection="department.employees" open="(" separator="," close=")" item="employee">
        #{employee.age}
    </foreach>
</select>

這裏foreach 對應Departmen部門中的List employees

請求參數: 查詢部門Id=1,並且年齡 等於24和25的員工

{
  "createTime": "2019-07-02T10:17:16.756Z",
  "deptName": "string",
  "descr": "string",
  "employees": [
    {
      "age": "24",
    },
    {
      "age": "25",
    }
  ],
  "id": 1
}

結果:

{
  "data": [
    {
      "address": "北新街ndcpc",
      "age": "24",
      "createTime": 1562062434000,
      "deptId": "1",
      "gender": 1,
      "id": "318397755696631808",
      "name": "kls0bx19cy"
    },
    {
      "address": "北新街lavi0",
      "age": "25",
      "createTime": 1562062436000,
      "deptId": "1",
      "gender": 1,
      "id": "318397755801489408",
      "name": "gj9q3ygikh"
    }
  ],
  "result": "SUCCESS",
  "resultCode": 200,
  "resultMsg": ""
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章