温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

模糊查询怎么使用mybatis来实现

发布时间:2020-11-21 15:54:00 来源:亿速云 阅读:151 作者:Leah 栏目:编程语言

模糊查询怎么使用mybatis来实现?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

mybatis中分页有3种方式来实现,通过sql语句(两种传参方式)来实现,通过mybatis 的 Rowbounds 来实现。

通过(自定义类型)传参 来实现分页:

映射文件:

<select id="findListBypage" parameterType="cn.wh.util.PageUtil" resultType="Role">
    select * from t_role limit #{index},#{size}
  </select>

测试代码:

/**
   * 通过自定义类型来传参 实现分页功能 需要新建一个类型
   */
  @Test
  public void testPage1(){
    PageUtil pu = new PageUtil();
    pu.setIndex(3);
    pu.setSize(3);
    List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.findListBypage", pu);
    for(Role r:list){
      System.out.println(r.getName());
    }
  }

通过map传参实现:
映射文件:

<select id="findListBypage" parameterType="map " resultType="Role">
    select * from t_role limit #{index},#{size}
  </select>

测试代码:

/**
   * 可以通过map来传参 这样可以不用新建新的类型
   */
  @Test
  public void testPage2(){
    Map<String,Integer> map = new HashMap<String,Integer>();
    map.put("index", 0);
    map.put("size", 3);
    List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.findListBypage", map);
    for(Role r:list){
      System.out.println(r.getName());
    }
  }

通过RowBounds来实现分页:
映射文件:

<select id="findAll" resultType="Role">
    select * from t_role
  </select>

测试代码:

/**
   * 使用rowBounds来实现分页
   */
  @Test
  public void testPage3(){
    //第一个参数 是index,开始下标
    //第二个参数 是size,每页显示记录数
    RowBounds bounds = new RowBounds(3, 3);
    List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.findAll", null,bounds);
    for(Role r:list){
      System.out.println(r.getName());
    }
  }

注意:通常情况下使用 Map 传参来实现分页

模糊查询
映射文件:

<select id="selectLike" parameterType="string" resultType="Role">
    select *from t_role where name like #{name}
  </select>

测试代码:

/**
   * 模糊查询
   */
  @Test
  public void testLike1(){
    List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.selectLike","%会员");
    for(Role r:list){
      System.out.println(r.getName());
    }
  }

第二种方式:

<select id="selectLike1" parameterType="string" resultType="Role">
    select *from t_role where name like concat(#{name},'%');
  </select>

测试代码:

/**
   * 模糊查询
   */
  @Test
  public void testLike2(){
    List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.selectLike1","黄");
    for(Role r:list){
      System.out.println(r.getName());
    }
  }

注意:通常使用第二种方式实现模糊查询

关于模糊查询怎么使用mybatis来实现问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI