• 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+"%'");//模糊查找格式处理
    

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


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

  • 相关阅读:
    Mybatis总结(mybatis plus待更新)
    maven配置(IDEA)quickstart,IDEA上maven细节配置
    (已解决)C3P0数据库使用配置文件链接,报错:com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector run
    angular--ng-template&ngTemplateOutlet的用法

    Array.from()和Array.of()用法
    Object.create()
    继承
    Object类型
    剩余参数
  • 原文地址:https://www.cnblogs.com/wangqilong/p/9417523.html
Copyright © 2020-2023  润新知