专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 实现MyBatis的分页

实现MyBatis的分页

更新时间:2021-12-20 09:46:47 来源:赢咖4 浏览575次

分页的实现

sql的分页语句为(第一个参数是当前页面的索引起始位置,第二个参数是显示的页数)

select  *  from  user  limit  #{startIndex},#{pageSize};
# startIndex: 起始位置,默认为 0 
# pageSize: 页面大小
# 如何计算当前页面索引的起始位置
# currentPage = (currentPage-1)* pageSize  

limit 实现分页

编写dao接口

//查询所有用户实现分页
List < User >  selectUserByLimit ( Map < String , Integer > map ) ;

编译mapper映射文件的方法(可以通过map封装参数,方便参数传递)

< select  id = " selectUserByLimit "  parameterType = " Map "  resultType = " User " >
    select * from mybatis.user limit #{startIndex},#{pageSize}
</选择>

创建了用于获取 sqlSession 对象的工具类,并使自动提交事务成为可能。

包装融为一体。MLXH 。实用程序;
进口组织。阿帕奇。伊比斯。约。资源;
进口组织。阿帕奇。伊比斯。会话。SqlSession ; 
进口组织。阿帕奇。伊比斯。会话。SqlSessionFactory ; 
进口组织。阿帕奇。伊比斯。会话。SqlSessionFactoryBuilder ;
导入java 。约。IO异常;
导入java 。约。输入流;
//mybatis工具类,重复代码的净化
public  class  MyBatisUtils  {
    //类变量不需要设置默认值;
    私有 静态SqlSessionFactory sqlSessionFactory ;
    static  { 
        //在maven中,所有的资源文件一般都放在resources目录下,我们可以直接获取。
        尝试 {
            字符串资源=  "mybatis-config.xml" ; 
            InputStream inputStream =资源。getResourceAsStream (资源);
            sqlSessionFactory =  new  SqlSessionFactoryBuilder ( ) 。构建(的inputStream ); 
        }  catch  ( IOException e )  { 
            e. 打印堆栈跟踪();
        } 
    } 
    //设置SqlSessionFactory的方法 public 
    public  static SqlSessionFactory getSqlSessionFactory ( ) { 
        return sqlSessionFactory ; 
    } 
    //带有事务自动提交功能的通用SqlSession方法
    public  static SqlSession getSqlSession ( ) { 
        //自动提交事务
        return sqlSessionFactory . openSession (真) ; 
    } 
}

测试(模拟分页数据参数:当前Page,page Size)

@Test 
public  void  selectUserByLimit ( ) {
    //创建sqlSession 
    SqlSessionFactory sqlSessionFactory = MyBatisUtils . getSqlSessionFactory ( ) ; 
    SqlSession sqlSession = sqlSessionFactory 。openSession ( ) ;
    //准备数据
    int currentPage =  2 ; //当前页面是什么?
    int pageSize =  2 ;  //页面大小
    Map < String , Integer > map =  new  HashMap < String , Integer > ( ) ; 
    地图。put ( "startIndex" , ( currentPage - 1 ) * pageSize ) ; 
    地图。put ( "pageSize" , pageSize ) ;
    //测试
    UserDao 映射器= sqlSession . getMapper ( userDAO的。类); 
    列表<用户>用户=映射器。selectUserByLimit (地图) ;
    for  (用户用户:用户) {
        系统。出来。打印(用户);
    }
    sqlSession 。关闭( ) ; //关闭连接
}

按 RowBounds 分页

1.写接口

//查询所有用户使用RowBounds 
List < User >  selectUserByRowBounds ( )实现分页;

2.编写Mapper映射文件

< select  id = " selectUserByRowBounds "  resultType = " User " >
    从 mybatis.user 中选择 *
</选择>

3.工具类同上(只是获取sqlSession对象很简单)

4.编写测试代码

@Test 
public  void  selectUserByRowBounds ( ) { 
    //创建sqlSession 
    SqlSessionFactory sqlSessionFactory = MyBatisUtils . getSqlSessionFactory ( ) ; 
    SqlSession sqlSession = sqlSessionFactory 。openSession ( ) ;
    int currentPage =  2 ;  //当前页面
    int pageSize =  2 ;  //页面大小
    RowBounds rowBounds =  new  RowBounds ( ( currentPage -  1 )  * pageSize , pageSize ) ;
    //注意getMapper不能和RowBounds
    一起
    使用//selectList: Receive a List //Select Map: Receive a Map 
    //selectOne: 当只接收一个对象
    List < User > users = sqlSession . selectList ( "com.MLXH.dao.UserDao.selectUserByRowBounds" , null , rowBounds ) ; 
    for  (用户用户:用户) {
        系统。出来。打印(用户);
    } 
}

两者的区别

rowBounds 的本质是封装limit。

limit在SQL层面实现分页,使用getMapper获取测试中的对象

RowBounds 在代码层面实现分页,创建 rowBounds 对象

注释开发

增删改查示例(详细代码和目录布局)可以看到对于UserDao接口,我们需要创建一个userMapper.xml来实现该接口并在其中写入sql语句。

接下来,我们使用注解来简化它们的代码操作。

包装融为一体。MLXH 。道;
进口玉米。MLXH 。波乔。用户;
进口组织。阿帕奇。伊比斯。注释。* ;
导入java 。UTIL 。列表;
公共 接口 UserDao  {
    //查询所有用户
    @Select ( "select * from user" ) 
    List < User >  getUserList ( ) ;
    //通过ID查询用户
    @Select ( "select * from user where id = #{id}" ) 
    User getUserById ( @Param ( "id" )  int id ) ;
    //添加用户
    @Insert ( "insert into user(id,name,pwd) values (#{id},#{name},#{pwd})" ) 
    int  addUser ( User user ) ;
    //修改用户信息
    @Update ( "update user set name = #{name}, pwd = #{pwd} where id = #{id}" ) 
    int  updateUser ( User user ) ;
    //删除用户
    @Delete ( "delete from user where id =#{uid}" ) 
    int  deleteUser ( @Param ( "uid" )  int id ) ;
}

用户道

包装融为一体。MLXH 。道;
进口玉米。MLXH 。波乔。用户;
进口组织。阿帕奇。伊比斯。注释。* ;
导入java 。UTIL 。列表;
公共 接口 UserDao  {
    //查询所有用户
    @Select ( "select * from user" ) 
    List < User >  getUserList ( ) ;
    //通过ID查询用户
    @Select ( "select * from user where id = #{id}" ) 
    User getUserById ( @Param ( "id" )  int id ) ;
    //添加用户
    @Insert ( "insert into user(id,name,pwd) values (#{id},#{name},#{pwd})" ) 
    int  addUser ( User user ) ;
    //修改用户信息
    @Update ( "update user set name = #{name}, pwd = #{pwd} where id = #{id}" ) 
    int  updateUser ( User user ) ;
    //删除用户
    @Delete ( "delete from user where id =#{uid}" ) 
    int  deleteUser ( @Param ( "uid" )  int id ) ;
}

@Param 是一个参数注解。输入参数为1时,默认为Param,但输入参数多于1时,在每个参数前加上@Param,标识为参数。

例如: int update(@Param("id") int id,@Param("name") String name,@Param("pwd") String pwd)

Mybatis 核心简介

<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE 配置
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        《http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<配置>
    <!--配置文件修改--> 
    < properties  resource = " database.properties " />
    <!--Mybatis 设置--> 
    < settings >
         <!--默认日志实现--> 
        <!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
        <!--Log4j实现--> 
        <设置 名称= " logImpl " 值= " LOG4J " /> 
    </设置>
    <!--配置别名--> 
    < typeAliases >
         <!--<typeAlias type="com.MLXH.pojo.User" alias="User"/>--> 
        <包 名= " com.MLXH.pojo " /> 
    </ 类型别名>
    <环境 默认= “开发” > 
        <环境 id = “开发” > 
            <事务管理器 类型= “ JDBC ” /> 
            <数据源 类型= “ POOLED ” > 
                <属性 名称= “驱动程序” 值= “ ${driver} ” /> 
                <属性 名称= " url " value = " ${url} " /> 
                < property  name = " username "  value = " ${username} " /> 
                < property  name = " password "  value = " ${password} " /> 
            </ dataSource > 
        </环境> 
    </环境>
    < mappers >
         <!--class 对应一个接口类-->
        <!--resource 一个接口类对应的映射文件-->
         < mapper  class = " com.MLXH.dao.UserDao " /> 
    </ mappers >
</配置>

这里我们将sqlSession对象的创建封装为一个工具方法,设置事务自动提交(sqlSession Factory.openSession(true))

工具类

包装融为一体。MLXH 。实用程序;
进口组织。阿帕奇。伊比斯。约。资源;
进口组织。阿帕奇。伊比斯。会话。SqlSession ; 
进口组织。阿帕奇。伊比斯。会话。SqlSessionFactory ; 
进口组织。阿帕奇。伊比斯。会话。SqlSessionFactoryBuilder ; 
导入java 。约。IO异常;
导入java 。约。输入流;
//mybatis工具类,重复代码的净化
public  class  MyBatisUtils  { 
    //类变量不需要设置默认值;
    私有 静态SqlSessionFactory sqlSessionFactory ;
    static  { 
        //在maven中,所有的资源文件一般都放在resources目录下,我们可以直接获取。
        尝试 {
            字符串资源=  "mybatis-config.xml" ; 
            InputStream inputStream =资源。getResourceAsStream (资源);
            sqlSessionFactory =  new  SqlSessionFactoryBuilder ( ) 。构建(的inputStream ); 
        }  catch  ( IOException e )  { 
            e . 打印堆栈跟踪();
        } 
    } 
    //设置SqlSessionFactory的方法 public 
    public  static SqlSessionFactory getSqlSessionFactory ( ) { 
        return sqlSessionFactory ;
    } 
    //带有事务自动提交功能的通用SqlSession方法
    public  static SqlSession getSqlSession ( ) { 
        //自动提交事务
        return sqlSessionFactory . openSession (真) ; 
    } 
}

测试

包装融为一体。MLXH 。道;
进口玉米。MLXH 。波乔。用户;
进口玉米。MLXH 。实用程序。MyBatisUtils ; 
进口组织。阿帕奇。伊比斯。会话。SqlSession ; 
进口组织。JUnit的。测试;
进口太阳。rmi . 服务器。单播服务器引用;
导入java 。UTIL 。列表;
公共 类 UserDaoTest  {
    @Test 
    public  void  getUserList ( ) { 
        SqlSession sqlSession = MyBatisUtils . getSqlSession ( ) ; //带自动提交事务
        UserDao mapper = sqlSession . getMapper ( userDAO的。类); 
        列表<用户> userList = mapper 。获取用户列表( ) ; 
        对于 (用户用户: userList ) {
            系统。出来。打印(用户);
        } 
        SQLSESSION 。关闭( ) ; //关闭sqlSession; 
    }
    @Test 
    public  void  getUserById ( ) { 
        SqlSession sqlSession = MyBatisUtils . getSqlSession ( ) ; //带自动提交事务
        UserDao mapper = sqlSession . getMapper ( userDAO的。类); 
        用户 user = mapper 。getUserById ( 1 ) ; 
        系统。出来。打印(用户);
        sqlSession 。关闭( ) ; //关闭sqlSession;
    }   
    @Test 
    public  void  addUser ( ) { 
        SqlSession sqlSession = MyBatisUtils . getSqlSession ( ) ; //带自动提交事务
        UserDao mapper = sqlSession . getMapper ( userDAO的。类); 
        用户用户= 新 用户(5 , “冷雪” , “寒雪” ); 
        int i =映射器。添加用户(用户);
        系统。出来。打印(我);
        sqlSession 。关闭( ) ; //关闭sqlSession; 
    }
    @Test 
    public  void  updateUser ( ) { 
        SqlSession sqlSession = MyBatisUtils . getSqlSession ( ) ; //带自动提交事务
        UserDao mapper = sqlSession . getMapper ( userDAO的。类); 
        User user =  new  User ( 5 ,  "暮光之城" ,  "木灵寒雪" ) ; 
        int i =映射器。更新用户(用户);
        系统。出来。打印(我);
        sqlSession 。关闭( ) ; //关闭sqlSession; 
    }
    @Test 
    public  void  deleteUser ( ) { 
        SqlSession sqlSession = MyBatisUtils . getSqlSession ( ) ; //带自动提交事务
        UserDao mapper = sqlSession . getMapper ( userDAO的。类); 
        int i =映射器。删除用户(5 );
        系统。出来。打印(我);
        sqlSession 。关闭( ) ; //关闭sqlSession; 
    } 
}

总结:如你所见,注解开发其实就是封装接口的mapper文件,在接口方法中加入sql语句。如果您对此比较感兴趣,想了解更多相关知识,可以关注一下赢咖4的MyBatis视频教程,教程内容通俗易懂,适合没有基础的小伙伴学习,希望对大家能够有所帮助。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>