- 在映射器的xml文件中select语句有一个配置项叫做parameterType,它用来表示这条语句接收的参数类型。当传递的参数只有一个时,非常简单,直接在等号后面写上参数的类型即可。但是实际查询语句可能需要多个条件,也就是多个参数。下面介绍传入多个参数的几种方法。
- 有四种方法可以实现,分别是使用map传参数、使用注解传参数、使用Java Bean传参数和使用混合方式传参数。第一种map的方式不实用,所以只介绍剩余三种。
- 我们介绍的案例是通过角色表的两列信息来进行查询。角色表对应的pojo定义如下:
import java.io.Serializable;
import org.apache.ibatis.type.Alias;
@Alias("role")
public class Role implements Serializable {
private static final long serialVersionUID = 598736524547906734L;
private Long id;
private String roleName;
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
使用注解方式传参数
- 接口方法定义如下:
public List<Role> findRolesByAnnotation(@Param("roleName") String rolename, @Param("note") String note);
- 对应的映射文件配置如下,此时不需要写parameterType。
<select id="findRolesByAnnotation" resultType="role">
select id,
role_name as roleName, note from t_role
where role_name like
concat('%', #{roleName}, '%')
and note like concat('%', #{note}, '%')
</select>
通过java bean传递参数
- 首先需要创建需要传递参数的pojo类:
public class RoleParams {
private String roleName;
private String note;
/**setter and getter**/
}
- 接口方法定义如下:
public List<Role> findRolesByBean(RoleParams roleParam);
- 对应的配置文件如下,参数处直接写RoleParams类的属性名字。
<select id="findRolesByBean" parameterType="RoleParams"
resultType="role">
select id, role_name as roleName, note from t_role
where
role_name like
concat('%', #{roleName}, '%')
and note like concat('%',
#{note}, '%')
</select>
- 查询时需要先定义一个RoleParams对象,将其传入接口方法。
sqlSession = SqlSessionFactoryUtils.openSqlSession();
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
RoleParams roleParam = new RoleParams();
roleParam.setNote("1");
roleParam.setRoleName("1");
List<Role> roles = roleMapper.findRolesByBean(roleParam);
混合方式传入参数
有时我们需要混合使用几种方式,例如查询一个角色,可以使用角色名字和备注进行查询,与此同时还要支持分页,而分页参数的pojo如下:
public class PageParams{
private int start;
private int limit;
/**setter and getter**/
}
这时候的接口方法如下,使用注释和java bean混合的方式。
public List<Role> findByMix(@Param("params") RoleParams roleParams, @Param("page") PageParams PageParam);
对应的配置文件如下,注意这里对参数的引用方式。
<select id="findByMix" resultType="role">
select id, role_name as
roleName, note from t_role
where role_name like
concat('%',
#{params.roleName}, '%')
and note like concat('%', #{params.note}, '%')
limit #{page.start}, #{page.limit}
</select>