概述
mybatis SQL语句设置多个参数的方法一共有三种:
1.散装的参数,需要使用@Param(“sql中参数占位符名称”)。
2.实体类封装参数,需保证SQL中的参数名能够对上实体类属性名。
3.map集合,需保证SQL中的参数名能够对上map集合的键名称。
方法一:散装参数
dao层接口
@Mapper
public interface UserMapper {
List<User> getMatchCount(String username, String password);
}
UserMapper.xml中对应的mapper
<select id="getMatchCount" resultType="User">
select *
from sys_user
where username=#{username} and password=#{password};
</select>
这里有一个点要注意,如果接口方法中的参数与sql中的参数名不同的话,需要@Param指定参数
@Mapper
public interface UserMapper {
List<User> getMatchCount(@Param("username") String n, @Param("password") String p);
}
方法二:实体类封装参数
假如需要传入的参数较多,可以使用一个pojo类封装参数,同时要注意实体类属性名能够对上SQL中的参数名。
@Mapper
public interface UserMapper {
List<User> getMatchCount2(@Param("param") ParamClass param);
}
这里使用了ParamClass一个普通的pojo类来封装参数。
<select id="getMatchCount2" resultType="User">
select *
from sys_user
where username=#{param.username} and password=#{param.password};
</select>
方法三:map集合
也可以使用map,需保证SQL中的参数名能够对上map集合的键名称。
@Mapper
public interface UserMapper {
List<User> getMatchCount3(Map<String, String> map);
}
<select id="getMatchCount3" resultType="User">
select *
from sys_user
where username=#{u} and password=#{p};
</select>
@Test
public void testGetMatchCount3(){
HashMap<String, String> map = new HashMap<>();
map.put("u", "zou");
map.put("p", "123");
List<User> list = userMapper.getMatchCount3(map);
System.out.println("list大小:"+list.size());
}