MyBatis | MyBatis中模糊查询LIKE的三种方式

目录

模糊匹配

写法1:直接将通配符拼接在参数上

写法2:使用MySQL提供的concat函数

写法3:使用bind标签处理


模糊匹配

字符串模糊匹配:使用 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方法。


以上都是学习过程中的总结,如果有错误或者有疑问,欢迎一起交流吖~~

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值