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

猜你喜欢

转载自blog.csdn.net/qq_36675851/article/details/89080857