单条件动态查询

**从多个条件中选择一个

   *choose(when,otherwise):选择,类似于Java中的switch语句

步骤一:创建方法类

 

/**
   *  单条件动态查询
   * @param brand
   * @return
   */
  List<Brand> selectByConditionSingle(Brand brand);

 步骤二:书写对应的select语句

 <select id="selectByConditionSingle" resultMap="brandResultMap">
        select *
        from tb_brand
        where
            <choose><!--choose相当于java里的switch,when相当于case,test是判断-->
                <when test="status != null">
                    status = #{status}
                </when>
                <when test="companyName != null and companyName != ''">
                    company_name like #{companyName}
                </when>
                <when test="brandName != null and brandName != ''">
                    brand_name like #{brandName}
                </when>
            </choose>
          <otherwise>
         1 = 1
          </otherwise>//保底的,如何用户什么也没选,不至于系统崩溃
    </select>

步骤三:修改测试类

  //单条件动态查询
     public void testselectByConditionSingle() throws IOException {
         //接受参数
         int status = 1;//现在是固定数据,以后会变成动态数据
         String companyName = "华为";
         String brandName = "华为";
         //处理参数,模糊查询需要自带百分号或者下划线,这样处理可以带上百分号
         companyName = "%" + companyName + "%";
         brandName = "%" + brandName + "%";

         //处理参数,定义一个关键字,将查询的关键字封装
         Brand brand = new Brand();
         brand.setStatus(status);
        /* brand.setCompanyName(companyName);
         brand.setBrandName(brandName);*/

         //1. 获取SqlSessionFactory
         String resource = "mybatis-config.xml";
         InputStream inputStream = Resources.getResourceAsStream(resource);
         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
         //2.获取Sqlsession对象
         SqlSession sqlSession = sqlSessionFactory.openSession();

         //3.获取Mapper接口的代理对象
         BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

         //4.执行方法
         List<Brand> brands = brandMapper.selectByConditionSingle(brand);
         System.out.println(brands);

         //5.释放资源
         sqlSession.close();
     }

修改的地方:1.参数brand设置

 

 

 2.执行方法调用打印brand

 

 

 牛逼的地方就是:它根据status这一个关键字进行了动态的模糊查询

 

posted @ 2023-03-27 01:14  YE-  阅读(34)  评论(0编辑  收藏  举报