一、基础
3、更多查询
(1)模糊查询
1. 修改Category.xml,提供listCategoryByName查询语句
<select id="listCategoryByName" parameterType="string" resultType="Category">
select * from category_ where name like concat('%',#{0},'%') <!--=这里#{0},0可能是占位符的作用-->
</select> <!--concat(str1,str2,str3,str4,……….); 连接字符串函数,会生成一个字符串 -->
2. 在TestMybatis.java中
List<Category> cs = session.selectList("listCategoryByName","cat");
for (Category c : cs) {
System.out.println(c.getName());
}
注:concat() 函数,是用来连接字符串。
精确查询: select * from user where name=”zhangsan”
模糊查询: select * from user where name like “%zhang%”
在实际的使用中,条件是作为参数传递进来的。 所以我们使用 concat() 函数
mybatis: select * from user where name like concat(“%”, #{name},”%”)
(2)多条件查询
1. 修改Category.xml
<select id="listCategoryByIdAndName" parameterType="map" resultType="Category">
select * from category_ where id> #{id} and name like concat('%',#{name},'%')
</select>
2. 在TestMybatis.java中
Map<String,Object> params = new HashMap<>();
params.put("id", 3);
params.put("name", "cat");
List<Category> cs = session.selectList("listCategoryByIdAndName",params);
for (Category c : cs) {
System.out.println(c.getName());
}