发布于 2017-08-26 21:36:08 | 189 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的MyBatis教程,程序狗速度看过来!

MyBatis 基于Java的持久层框架

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。


这篇文章主要为大家详细为大家详细介绍了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());
    }
  }

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

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



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务