欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mybatis分页及模糊查询功能实现

程序员文章站 2024-02-15 10:08:40
mybatis中分页有3种方式来实现,通过sql语句(两种传参方式)来实现,通过mybatis 的 rowbounds 来实现。 通过(自定义类型)传参 来实现分页:...

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());
    }
  }

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。