mybatis模糊查询

模糊查询在我们开发中是一项必不可缺少的重要内容。对于我们mybatis实现模糊查询有三种方式,以下具体的实现步聚:

1. 添加模糊查询的接口方法getStudentBySname

  1. List<Student> getStudentBySname1(String sname);
  2. List<Student> getStudentBySname2(String sname);
  3. List<Student> getStudentBySname3(String sname);

2.配置接口方法对应的sql文件

1) 配置占位符方式#{}

  1. <select id="getStudentBySname" parameterType="String" resultType="com.etime.pojo.Student">
  2. select * from student where sname like #{sname};
  3. </select>

2) 配置拼接字符串方式${}

  1. <select id="getStudentBySname2" parameterType="String" resultType="com.etime.pojo.Student">
  2. select * from student where sname like '%${value}%';
  3. </select>

我们在上面将原来的#{}占位符,改成了${value}。注意如果用模糊查询的这种写法,那么${value} 的写法就是固定的,不能写成其它名字。

3) 配置mysql函数方式concat

  1. <select id="getStudentBySname3" parameterType="String" resultType="com.etime.pojo.Student">
  2. select * from student where sname like concat('%',#{sname},'%');
  3. </select>

3. 模糊查询测试

  1. @Test
  2. public void t01() {
  3. SqlSession sqlSession = SqlSessionUtil.getSqlSession();
  4. StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
  5. String name = "安";
  6. String sname = "%" + name + "%";//最常用
  7. List<Student> list = studentDao.getStudentBySname1(sname);
  8. list.forEach(System.out::println);
  9. SqlSessionUtil.closeSqlSession(sqlSession);
  10. }
  11. @Test
  12. public void t02() {
  13. SqlSession sqlSession = SqlSessionUtil.getSqlSession();
  14. StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
  15. String sname = "安";
  16. List<Student> list = studentDao.getStudentBySname2(sname);
  17. list.forEach(System.out::println);
  18. SqlSessionUtil.closeSqlSession(sqlSession);
  19. }
  20. @Test
  21. public void t03() {
  22. SqlSession sqlSession = SqlSessionUtil.getSqlSession();
  23. StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
  24. String sname = "安";
  25. List<Student> list = studentDao.getStudentBySname3(sname);
  26. list.forEach(System.out::println);
  27. SqlSessionUtil.closeSqlSession(sqlSession);
  28. }

 查询结果:

posted @ 2023-11-14 20:21  echosada  阅读(485)  评论(0)    收藏  举报