方法一:
使用拼接的方式直接创建一个含有'%'的字符串
<!--第一种 like , java代码指定 like的内容--> <select id="selectLikeOne" resultType="com.bjpowernode.domain.Student"> select id,name,email,age from student where name like #{name} </select>
@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("#######学生="+stu); } sqlSession.close(); }
方法二:
直接在映射文件中添加上'%'符号
<!--第二种方式:在mapper文件中拼接 like的内容--> <select id="selectLikeTwo" resultType="com.bjpowernode.domain.Student"> select id,name,email,age from student where name like "%" #{name} "%" </select>
@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("*******学生="+stu); } sqlSession.close(); }
总结:推荐使用第一种方式,方法二过于死板,第一种动态性更好,可以根据自己需求进行模糊查询