模糊查询的实现有两种方式, 一是 java 代码中给查询数据加上“%” ; 二是在 mapper 文件 sql 语句的条件位置加上“%”

需求:查询姓名有“帅”的

例1:java代码中提供要查询的 “%帅%”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//接口方法:
List<Student> selectLikeFirst(String name);

//mapper 文件:
<select id="selectLikeFirst" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student
where name like #{studentName}
</select>

//测试方法:
@Test
public void testSelectLikeOne(){
String name="%帅%";
List<Student> stuList = studentDao.selectLikeFirst(name);
stuList.forEach( stu -> System.out.println(stu));
}

例2:mapper文件中使用 like name “%” #{xxx} “%”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//接口方法:
List<Student> selectLikeSecond(String name);

//mapper 文件:
<select id="selectLikeSecond" resultType="com.bjpowernode.domain.Student">
select id,name,email,age from student
where name like "%" #{studentName} "%"
</select>

//测试方法:
@Test
public void testSelectLikeSecond(){
String name="帅";
List<Student> stuList = studentDao.selectLikeSecond(name);
stuList.forEach( stu -> System.out.println(stu));
}