Mybatis的分页查询

Mybatis的分页查询

(1)无条件的分页

mapper文件配置和Java代码实现


    <select id="findByPage" parameterType="map" resultMap="studentMap">
        select id,name,age,sex from student
        limit #{start},#{end}
    select>
/*
     * 无条件分页查询
     */
    public List findByPage(int start,int end)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            Map param = new LinkedHashMap();
            param.put("start",start);
            param.put("end",end);
            
            List 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 findByPageAndRequest(String name,int start,int end)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            Map params = new LinkedHashMap();
            //当sql的条件有模糊匹配时,参数需前后带上%
            params.put("name", "%"+name+"%");
            params.put("start", start);
            params.put("end", end);
            
            List 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的分页查询)