在mybatis中模糊查询的实现有两种方式,一是Java代码中给查询数据加上“%” ; 二是在mapper文件sql语句的位置加上“%”
1.在接口中定义两个方法
/*第一种模糊查询*/ List<Student> selectLikeOne(String name); /*第二种模糊查询 * name就是李值,在mapper中拼接like "%" 李 "%"*/ List<Student> selectLikeTwo(String name);
2.在mapper文件中编写方法的映射信息
<!--第一种like, java代码中指定like内容--> <select id="selectLikeOne" resultType="com.example.domain.Student"> select id, name, email, age from student where name like #{name} </select> <!--第二种like,在mapper文件中拼接 like内容--> <select id="selectLikeTwo" resultType="com.example.domain.Student"> select id, name, email, age from student where name like "%" #{name} "%" </select>
3.编写测试方法
@Test public void testSelectLikeOne(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); //准备好like的内容 String name = "%李%"; List<Student> students = dao.selectLikeOne(name); for(Student stu : students){ System.out.println("student:"+stu); } sqlSession.close(); } @Test public void testSelectLikeTwo(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); //准备好like的内容 String name = "李"; List<Student> students = dao.selectLikeTwo(name); for(Student stu : students){ System.out.println("student:"+stu); } sqlSession.close(); }
4.总结
推荐第一种方式,灵活性高,而且可读性强