模糊查询在我们开发中是一项必不可缺少的重要内容。对于我们mybatis实现模糊查询有三种方式,以下具体的实现步聚:
1. 添加模糊查询的接口方法getStudentBySname
- List<Student> getStudentBySname1(String sname);
- List<Student> getStudentBySname2(String sname);
- List<Student> getStudentBySname3(String sname);
2.配置接口方法对应的sql文件
1) 配置占位符方式#{}
- <select id="getStudentBySname" parameterType="String" resultType="com.etime.pojo.Student">
- select * from student where sname like #{sname};
- </select>
2) 配置拼接字符串方式${}
- <select id="getStudentBySname2" parameterType="String" resultType="com.etime.pojo.Student">
- select * from student where sname like '%${value}%';
- </select>
我们在上面将原来的#{}占位符,改成了${value}。注意如果用模糊查询的这种写法,那么${value} 的写法就是固定的,不能写成其它名字。
3) 配置mysql函数方式concat
- <select id="getStudentBySname3" parameterType="String" resultType="com.etime.pojo.Student">
- select * from student where sname like concat('%',#{sname},'%');
- </select>
3. 模糊查询测试
- @Test
- public void t01() {
- SqlSession sqlSession = SqlSessionUtil.getSqlSession();
- StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
- String name = "安";
- String sname = "%" + name + "%";//最常用
- List<Student> list = studentDao.getStudentBySname1(sname);
- list.forEach(System.out::println);
- SqlSessionUtil.closeSqlSession(sqlSession);
- }
-
- @Test
- public void t02() {
- SqlSession sqlSession = SqlSessionUtil.getSqlSession();
- StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
- String sname = "安";
- List<Student> list = studentDao.getStudentBySname2(sname);
- list.forEach(System.out::println);
- SqlSessionUtil.closeSqlSession(sqlSession);
- }
-
- @Test
- public void t03() {
- SqlSession sqlSession = SqlSessionUtil.getSqlSession();
- StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
- String sname = "安";
- List<Student> list = studentDao.getStudentBySname3(sname);
- list.forEach(System.out::println);
- SqlSessionUtil.closeSqlSession(sqlSession);
- }
查询结果:
标签:SqlSessionUtil,sname,String,StudentDao,模糊,List,查询,sqlSession,mybatis From: https://www.cnblogs.com/echosada/p/17830082.html