MyBatis | MyBatis中模糊查询LIKE的三种方式
模糊匹配
字符串模糊匹配:使用 like 关键字 %:表示一个或者是多个字符 _:表示一个字符
需求:查询student表中用户名含豆的所有用户
select * from student where Sname like %豆%;
写法1:直接将通配符拼接在参数上
1.xml文件中:
<select id="selectStudentByName" resultMap="studentMap"> select * from student where Sname like #{name} </select>
2.测试:
@Test public void selectStudentByName(){ //获取会话 SqlSession sqlSession = sqlSessionFactory.openSession(); //通过接口获取对象实例 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); List<Student> students = studentMapper.selectStudentByName("%豆%"); Iterator<Student> iterator = students.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } }
3.执行结果:
写法2:使用MySQL提供的concat函数
MySQL提供字符串拼接的方法:concat(x1,x2) --->x1x2
1.xml文件中:
<select id="selectStudentByName" parameterType="string" resultType="student"> select * from student where Sname like concat(%,concat(#{name},%)) </select>
2.测试方法中:
List<Student> students = studentMapper.selectStudentByName("豆");
3.执行结果:
写法3:使用bind标签处理
1.xml文件中:
<select id="selectStudentByName" resultType="student"> <bind name="namesql" value="%+name+%"/> select * from student where Sname like #{namesql} </select>
2.测试方法中:
List<Student> students = studentMapper.selectStudentByName("豆");
3.执行结果:
注意:bind表达式中value属性处理中借助OGNL表达式,对应的参数需要具有getter方法。
以上都是学习过程中的总结,如果有错误或者有疑问,欢迎一起交流吖~~