Spring在依赖注入bean的时候,会把所有实现MyBatis中Interceptor接口的所有类都注入到SqlSessionFactory中,作为plugin存在。既然如此,我们集成一个plugin便很简单了,只需要使用@Bean创建PageHelper对象即可。
1.创建数据库
create table t_book
(
book_id int primary key auto_increment, -- ID
book_name varchar(50) not null, -- 书名
book_price float not null, -- 价格
book_brief varchar(256) -- 简介
);-- 记得添加数据
2.pom.xml中添加集成Mybatis分页的相关依赖
<!--Spring Boot集成MyBatis分页-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
3.创建实体类
package com.king.s5.model;
public class Book {
private Integer bookId;
private String bookName;
private Float bookPrice;
private String bookBrief;
public Book(Integer bookId, String bookName, Float bookPrice, String bookBrief) {
this.bookId = bookId;
this.bookName = bookName;
this.bookPrice = bookPrice;
this.bookBrief = bookBrief;
}
public Book() {
super();
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Float getBookPrice() {
return bookPrice;
}
public void setBookPrice(Float bookPrice) {
this.bookPrice = bookPrice;
}
public String getBookBrief() {
return bookBrief;
}
public void setBookBrief(String bookBrief) {
this.bookBrief = bookBrief;
}
@Override
public String toString() {
return "Book{" +
"bookId=" + bookId +
", bookName='" + bookName + '\'' +
", bookPrice=" + bookPrice +
", bookBrief='" + bookBrief + '\'' +
'}';
}
}
4.创建接口和实现类
public interface IBookBiz {
void addBook(Book book);
List<Book> listBooks(Book book, PageBean pageBean);
}
package com.king.s5.biz.impl;
import com.king.s5.biz.IBookBiz;
import com.king.s5.mapper.BookMapper;
import com.king.s5.model.Book;
import com.king.s5.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookBizImpl implements IBookBiz {
@Autowired
private BookMapper bookMapper;
@Override
public void addBook(Book book) {
bookMapper.insertSelective(book);
}
@Override
public List<Book> listBooks(Book book, PageBean pageBean) {
return bookMapper.listBooks(book);
}
}
注意:mapper中的类和xml我就不写了,可以用mybatis插件-mybatis-generator自动生成,需要学习的可以在在下方留言
5.创建测试类
1.先创建一个baseCaseTest(公共的基础类),可以减少代码量,进行代码优化。
package com.king.s5;
import com.github.pagehelper.PageHelper;
import com.king.s5.biz.IBookBiz;
import com.king.s5.model.Book;
import com.king.s5.util.PageBean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class BaseCaseTest{
protected Book book;
protected PageBean pageBean;
@Before
public void setUp() throws Exception {
book = new Book();
pageBean = new PageBean();
}
@After
public void tearDown() throws Exception {
}
}
2.注册一个MyBatis分页插件PageHelper的实体类
package com.king.s5.util;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.pagehelper.PageHelper;
/**
* mybatis配置类.
* @author Angel baby--守护天使
* @version v.0.1
* @date 2018年4月8日
*/
@Configuration
public class MyBatisConfiguration {
/**
* 注册MyBatis分页插件PageHelper
* @return
*/
@Bean
public PageHelper pageHelper() {
System.out.println("MyBatisConfiguration.pageHelper()");
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
3.添加分页所需要的工具类
package com.king.s5.util;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;
public class PageBean implements Serializable {
private static final long serialVersionUID = -7544706514503688395L;
private int curPage = 1;// 当前页
private int pageRecord = 2;// 页大小
private int totalRecord;// 总记录数
private boolean paginate = true;/* 是否分页,默认分页 */
private String url;
private Map<String, String[]> parameterMap;
public PageBean() {
super();
}
/**
* 初始化分页数据
*
* @param request
*/
public void setRequest(HttpServletRequest request) {
this.setCurPage(request.getParameter("curPage"));
this.setPageRecord(request.getParameter("pageRecord"));
this.setPaginate(request.getParameter("paginate"));
this.url = request.getContextPath() + request.getServletPath();
this.parameterMap = request.getParameterMap();
// 兼容easyui的页码page、页大小rows
String rows = request.getParameter("rows");
String page = request.getParameter("page");
if (null != rows && null != page) {
this.setCurPage(request.getParameter("page"));
this.setPageRecord(request.getParameter("rows"));
}
}
public boolean isPaginate() {
return paginate;
}
public void setPaginate(boolean paginate) {
this.paginate = paginate;
}
public void setPaginate(String paginate) {
paginate = null == paginate ? "" : paginate.trim();
if ("false".equalsIgnoreCase(paginate)) {
this.paginate = false;
} else {
this.paginate = true;
}
}
private void setPageRecord(String pageRecord) {
if (null != pageRecord && !"".equals(pageRecord.trim())) {
this.pageRecord = Integer.parseInt(pageRecord);
}
}
private void setCurPage(String curPage) {
if (null != curPage && !"".equals(curPage.trim())) {
this.curPage = Integer.parseInt(curPage);
}
}
public String getUrl() {
return url;
}
public void setCurPage(int curPage) {
this.curPage = curPage;
}
public void setPageRecord(int pageRecord) {
this.pageRecord = pageRecord;
}
public Map<String, String[]> getParameterMap() {
return parameterMap;
}
public int getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(int totalRecord) {
this.totalRecord = totalRecord;
}
public void setTotalRecord(String totalRecord) {
this.totalRecord = Integer.valueOf(totalRecord);
}
public int getCurPage() {
return curPage;
}
public int getPageRecord() {
return pageRecord;
}
public int getMaxPageNumber() {
int maxPageNumber = this.totalRecord / this.pageRecord;
maxPageNumber = totalRecord % pageRecord == 0 ? maxPageNumber : maxPageNumber + 1;
return maxPageNumber;
}
public int getNextPageNumber() {
int nextPageNumber = this.curPage + 1;
nextPageNumber = nextPageNumber > this.getMaxPageNumber() ? this.getMaxPageNumber() : nextPageNumber;
return nextPageNumber;
}
public int getPreviousPageNumber() {
int previousPageNumber = this.curPage - 1;
previousPageNumber = previousPageNumber < 1 ? 1 : previousPageNumber;
return previousPageNumber;
}
public int getStartIndex() {
return (this.curPage - 1) * this.pageRecord;
}
public int getEndIndex() {
return this.curPage * this.pageRecord - 1;
}
@Override
public String toString() {
return "PageBean [curPage=" + curPage + ", pageRecord=" + pageRecord + ", totalRecord=" + totalRecord + "]";
}
}
4.创建实现类的测试类
package com.king.s5.biz.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.king.s5.BaseCaseTest;
import com.king.s5.BaseTest;
import com.king.s5.biz.IBookBiz;
import com.king.s5.model.Book;
import com.king.s5.util.PageBean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class BookBizImplTest extends BaseCaseTest {
@Autowired
private IBookBiz bookBiz;
// private Book book;
// private PageBean pageBean;
//
// @Before
// public void setUp() throws Exception {
// book = new Book();
// pageBean = new PageBean();
// }
//
// @After
// public void tearDown() throws Exception {
// }
@Override
public void setUp() throws Exception {
super.setUp();
}
@Test
public void addBook() throws Exception {
}
@Test
public void listBooks() throws Exception {
PageHelper.startPage(pageBean.getCurPage(),pageBean.getPageRecord());//curPage起始页,pageRecored页大小
List<Book> appsList = bookBiz.listBooks(book,pageBean);
// 需要把Page包装成PageInfo对象才能序列化。该插件也默认实现了一个PageInfo
// PageInfo<Book> pageInfo = new PageInfo<Book>(appsList);
// System.out.println(appsList+" =========== ");
for(Book b:appsList){
System.out.println(b);
}
// System.out.println(pageInfo);
}
}
注意:如果项目报错,出不来,是因为没有加相应的注解,如果加了还出不来,那就是你哪一个环节有问题
application.properties中配置mybatis | mybatis.mapper-locations=classpath*:mapper/*.xml#加载映射 |
springApplication类中加 | @SpringBootApplication |
springApplication类中加 | @MapperScan("com.king.s5.mapper")//将项目中对应的mapper类的路径加进来就可以了 |
springboot的一些注解
@SpringBootApplication | 申明让spring boot自动给程序进行必要的配置,这个配置等同于:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三个配置。 |
@Configuration | 等同于spring的XML配置文件;使用Java代码可以检查类型安全。 |
@Component | 可配合CommandLineRunner使用,在程序启动后执行一些基础任务。 |
@Autowired | 自动导入。 |
@PathVariable | 获取参数。 |
@Bean | 用@Bean标注方法等价于XML中配置的bean。 |
@Value | 注入Spring boot application.properties配置的属性的值 |
@Controller | 用于定义控制器类,在spring 项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),一般这个注解在类中,通常方法需要配合注解@RequestMapping |
@ResponseBody | 比如异步获取json数据,加上@responsebody后,会直接返回json数据 |
想要源码的,可以到我的资源库下载 点击打开链接
--------------如果大家喜欢我的博客,可以点击左上角的关注哦。