myBatis模糊查找

对数据库条件查找,进行姓名模糊查找,我使用的是mysql数据库
正常语句:select * from student where 1=1 and name like ‘%name%’;
蓝色name是从service层得到的名字,即需要模糊查找的内容,这里要注意模糊查找格式:like ‘%查找的内容%’


方法一、在xml中对模糊查找的处理
下面是myBatis.xml文件中对模糊查找的配置语句

<!--条件查找、模糊查询,如果名字不为空对名字进行模糊查找 -->
<select id="findByCondition" resultType="com.wql.Student"
        parameterType="com.wql.Student">
        select * from student where 1=1
        <if test="name!=null">
            and name like '%${name}%'
        </if>
    </select>

上面的处理方式是在xml中对模糊查找的处理,格式为:‘%${name}%’
这里必须是$符号,要原样输出,不可以为#号。


方法二、在处理层解决

public class TestEnd {
    public static void main(String[] args) {
        ServiceDao sd=new ServiceDaoImpl();
        //sd.add(new Student(7,"殇滘",21,"男"));

        //模糊查找
        List<Student> list=sd.findByCondition(new Student(7,"'%王%'",21,"男"));

        System.out.println(list);
        List<Student> listAll=sd.findAll();
        System.out.println(listAll);
    }
}

List list=sd.findByCondition(new Student(7,”’%王%’”,21,”男”));
直接在传入数据时对姓名处理,格式:‘%王%’
这种处理方式在xml文件中就不要方法一那种写法了

<!--条件查找、模糊查询,如果名字不为空对名字进行模糊查找 -->
    <select id="findByCondition" resultType="com.wql.Student"
        parameterType="com.wql.Student">
        select * from student where 1=1
        <if test="name!=null">
            and name like ${name}
        </if>
    </select>

方法三、在myBatis的DbUtils的数据库具体操作实现层处理
这里写图片描述

public List<Student> findByCondition(Student s) {
        String name=s.getName();//得到姓名
        s.setName("'%"+name+"%'");//模糊查找格式处理
        String namespace="com.studentDao.ServiceDao";
        SqlSession sqlSession=MyBatisUtils.getSqlSession();
        return sqlSession.selectList(namespace+".findByCondition", s);
    }
String name=s.getName();//得到姓名
s.setName("'%"+name+"%'");//模糊查找格式处理

处理方式,先得到姓名,在对姓名进行处理格式


上面三种方式推荐使用第一种和第二种方式,因为这两种方式是一劳永逸的,
我个人喜欢第一种方式

转载于:https://www.cnblogs.com/wangqilong/p/8279758.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值