Mybatis 傳遞參數示例

1.        單參數且非集合

若映射器中的方法只有一個參數,並且不是List或者數組等集合類型,則在對應的SQL語句中,可以採用#{參數名}的方式來引用此參數。

示例:

DAO :

public User selectByUserId(Long userId);

Mapper.xml :

<select id="selectByUserId" parameterType="java.lang.Long" resultMap="UserResultMap">
  select *
  from tb_user
  where user_id = #{userId}
</select>

 

2.     多參數且非集合

可以看看這篇文章

http://www.2cto.com/database/201409/338155.html

示例:

使用@Param註解傳遞多個參數給Mybatis,查詢指定公司指定部門的所有用戶

DAO :

public List<User> selectByCompanyIdAndDepartmentId ( @Param(“companyId”) Long companyId, @Param(“departmentId”) Long departmentId);

Mapper.xml :

<select id="selectByCompanyIdAndDepartmentId" resultMap="UserResultMap">
  select *
  from tb_user
  where company_id = #{companyId} and department_id = #{departmentId}
</select>

 

3.        單參數且爲集合類

你可以將一個 List 實例或者數組作爲參數對象傳給 MyBatis,當你這麼做的時候,MyBatis 會自動將它包裝在一個 Map 中,List 實例將會以“list”作爲鍵,而數組實例的鍵將是“array”。

示例:

根據userIds批量查詢用戶

DAO :

public List<User> selectBatch (List<Long> userIds);

Mapper.xml :

<select id="selectBatch" resultMap="UserResultMap">
  select *
  from tb_user
<if test="userIds != null">
  where user_id in 
<foreachcollection="list" item="userId" open="(" separator="," close=")">
    #{userId}
    </foreach>
</if>
</select>

 

4.        多參數且其中有多個集合類

假設要定義一個DAO方法,用於查詢多家公司中的多個部門中名字中含有某些關鍵字的用戶信息。用戶表tb_user包含用戶所在公司的company_id字段和所在部門的 department_id 字段。

現在就需要傳遞多個List和一個String參數。

示例:

DAO :

/**

 * Map需要如下item

 * params.put(“companyIds”, companyIdList);

* params.put(“departmentIds”, departmentIdList);

* params.put(“keyword”, keyword);

*/

public List<User> selectBySearchFields (Map<String, Object> params);

或者是下面這樣,@Param也可以傳遞多個List參數給Mybatis

public List<User> selectBySearchFields (@Param("companyIds") List<Long> companyIds,

                              @Param("departmentIds") List<Long> departmentIds,

                            @Param("keyword ") String keyword);

 

Mapper.xml :注意collection的參數

<select id="selectBySearchFields" resultMap="UserResultMap">
  select *
  from tb_user
  where 1=1
<if test="companyIds != null">
  and company_id in
<foreachcollection="companyIds" item="companyId" open="(" separator="," close=")">
    #{companyId}
    </foreach>
</if>
<if test=" departmentIds!= null">
  and department_id in
<foreachcollection="departmentIds" item="departmentId" open="(" separator="," close=")">
    #{departmentId}
    </foreach>
</if>
<if test=" departmentIds!= null">
  and user_nameLIKE CONCAT('%',#{keyword},'%')
</if>
</select>

 

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