1. 程式人生 > >MyBatis分頁的簡單實現

MyBatis分頁的簡單實現

使用spring+springmvc+mybatis實現簡單的分頁查詢
spring+springmvc+mybatis的整合配置就不在贅述了

1.需要下載pagehelper-3.2.1.jar
2.po層—News.java

package com.ssm.po;

import java.util.Date;

public class News {

    private int id;
    private int academyId;
    private String title;
    private Date time;
    private String content;
    private
String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAcademyId() { return academyId; } public void setAcademyId(int academyId) { this.academyId = academyId; } public String getTitle
() { return title; } public void setTitle(String title) { this.title = title; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getContent() { return content; } public
void setContent(String content) { this.content = content; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }

3.mapper層—NewsMapper.java

public List<News> listAllNews();

**4.mapper的配置檔案—NewsMapper.xm**l

<!--列出所有新聞資訊 -->
    <select id="listAllNews" resultType="News">
        select id,academyId,title,time,content,address from news
    </select>

5.mybatis的配置資訊—sqlMapConfig.xml
在mybatis的配置中新增pagehelper的外掛配置
sqlMapConfig.xml

<plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 設定資料庫型別 -->
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>

6.service層的開發—NewsService.java

public List<News> listAllNews();

7.service的實現類—NewsServiceImpl.java

    @Autowired
    private NewsMapper newsMapper;

    @Override
    public List<News> listAllNews() {
        // TODO Auto-generated method stub
        return newsMapper.listAllNews();
    }

8.測試類的開發

private static ApplicationContext applicationContext;

    private static NewsMapper newsMapper;

    private static NewsService newsService;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        applicationContext = new ClassPathXmlApplicationContext(
                "classpath:spring/applicationContext-dao.xml");
        newsMapper = (NewsMapper) applicationContext.getBean("newsMapper");

    }

// 列出所有新聞資訊
    @Test
    public void testListAllNews() {

        PageHelper.startPage(1, 5);
        List<News> listNews = newsMapper.listAllNews();
        for (News news : listNews) {
            System.out.println(news.getId() + "--" + news.getTime() + "---"
                    + news.getAcademyId() + "--" + news.getTitle() + "--"
                    + news.getContent() + "--" + news.getAddress());
        }
        System.out.println(listNews.size());
    }

@AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

9.測試結果
測試結果

總結:上述步驟只是簡單的實現了分頁功能,而且需要手動設定頁數的大小,無法靈活的進行分頁。