Mybatis-Plus实现分页

1、导入maven依赖

springboot版本 2.7.3

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>

yml配置

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_
      id-type: auto
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

2、配置类

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MPConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}

3、dao层

@Mapper
public interface BookDao extends BaseMapper<Book> {

}

4、service层

 public interface BookService extends IService<Book> {
   IPage<Book> getPage(int currentPage, int pageSize, Book book);
}

5、serviceImpl层

@Service
public class BookServiceImpl extends ServiceImpl<BookDao, Book> implements BookService {

    @Autowired
    private BookDao bookDao;

    @Override
    public IPage<Book> getPage(int currentPage, int pageSize, Book book) {
        QueryWrapper<Book> qw = new QueryWrapper<>();
        qw.like(Strings.isNotEmpty(book.getType()),"type",book.getType());
        qw.like(Strings.isNotEmpty(book.getName()),"name",book.getName());
        qw.like(Strings.isNotEmpty(book.getDescription()),"description",book.getDescription());
        IPage<Book> page = new Page<>(currentPage,pageSize);
        bookDao.selectPage(page,qw);
        return page;
    }

}

6、Controller层

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Book book) {
        IPage<Book> page = bookService.getPage(currentPage, pageSize,book);
        if (currentPage > page.getPages()) {
            page = bookService.getPage((int) page.getPages(), pageSize,book);
        }
        return new R(true, page);
    }
}

时间:2022-10-11 午休

posted @ 2022-10-11 13:39  有何和不可  阅读(300)  评论(0)    收藏  举报