首页 > 其他 > 详细

Mybatis的分页查询

时间:2020-04-25 13:57:41      阅读:53      评论:0      收藏:0      [点我收藏+]

Mybatis的分页查询

(1)无条件的分页

mapper文件配置和Java代码实现

<!-- 传入的参数类型为map,此时无需使用map.get("key")去获得实际值,只需填入key值便可 -->
    <select id="findByPage" parameterType="map" resultMap="studentMap">
        select id,name,age,sex from student
        limit #{start},#{end}
    </select>
/*
     * 无条件分页查询
     */
    public List<Student> findByPage(int start,int end)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            Map<String,Object> param = new LinkedHashMap<String,Object>();
            param.put("start",start);
            param.put("end",end);
            
            List<Student> stuList;
            stuList = sqlSession.selectList(Student.class.getName()+".findByPage", param);
            
            System.out.println("添加查询成功");
            
            return stuList;
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

(2)有条件的分页

mapper文件配置和Java代码实现

<select id="findByPageAndRequest" parameterType="map" resultMap="studentMap">
        select id,name,age,sex from student
        where name like #{name}
        limit #{start},#{end}
    </select>

 

/*
     * 有条件分页查询
     */
    public List<Student> findByPageAndRequest(String name,int start,int end)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            Map<String,Object> params = new LinkedHashMap<String,Object>();
            //当sql的条件有模糊匹配时,参数需前后带上%
            params.put("name", "%"+name+"%");
            params.put("start", start);
            params.put("end", end);
            
            List<Student> stuList;
            stuList = sqlSession.selectList(Student.class.getName()
                    +".findByPageAndRequest", params);
            
            System.out.println("添加查询成功");        
            return stuList;
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

 

Mybatis的分页查询

原文:https://www.cnblogs.com/linhongwenBlog/p/12772586.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!