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