博客分页-根据是否发布来查询数据

1.Dao层根据是否发布(isEnable)来查询数据并携带pagebale分页信息

public interface ArticleDao extends JpaRepository<Article,Long>, JpaSpecificationExecutor<Article> {

    Page<Article> findAllByIsEnable(Integer isEnable, Pageable pageable);

}

2. service层构建分页信息和返回dao查询到的数据

page 表示当前页,size表示每页记录数,sort为排序方式

Constants.YES为定义好的常量,值为1;

在数据库中isEnable为是否发布,发布值为1,未发布值为0

@Service
public class ArticleServiceImpl implements ArticleService 
{
	@Override
    @Cacheable(value = "blogArticle", key = "#page")//开启缓存
    public Page<Article> findBlogArticleList(int page, int size) {
        //page 当前页,size 每页记录数
        Pageable pageable =new  PageRequest(page, size, Sort.Direction.DESC, "articleId");
        return articleDao.findAllByIsEnable(Constants.YES, pageable);
    }
}

controller层根据pageNumber作为页码进行分页查询

@PathVariable 用来接收前端页面的输入数据

articleService.findBlogArticleList( );第一个参数为当前页,第二个参数为每页的数量; 注意的是,jpa的pageable中,page参数表示当前为第几页,是从0开始,page=0表示第一页,以此类推

Constants.defaultPageSize定义的常量,值为5

@Controller
public class BlogController 
{
@Autowired
    private ArticleService articleService;
    @RequestMapping("/blog"})
    public String blog(Model model) {
        return this.blog(model, 1);
    }

    @GetMapping("/blog/{pageNumber}")
    public String blog(Model model, @PathVariable Integer pageNumber) {
        if (pageNumber == null) {
            pageNumber = 1;
        }
        Page<Article> articlePage = articleService.findBlogArticleList(pageNumber-1,Constants.defaultPageSize );
        List<Article> articleList = articlePage.getContent();
        model.addAttribute("articleList", articleList);
        model.addAttribute("totalCount", articlePage.getTotalElements());
        model.addAttribute("pageNumber", pageNumber);
        return "blog";
    }
}

这里对service层的@Cacheable做个说明

@Cacheable是spring Cache缓存的一部分,spring Cache缓存的核心思想是:当我们在调用一个缓存方法时,会把该方法参数和返回结果作为一个键值对存放在缓存中,等到下次利用同样的参数来调用该方法时将不再执行该方法,而是直接从缓存中获取结果进行返回

@Cacheable注解用于标记缓存,也就是对使用@Cacheable注解的位置进行缓存,对于使用@Cacheable标记的方法,spring在每次调用方法前都会根据key查询当前Cache中是否存在相key的缓存元素,如果存在就直接从缓存中获取结果并返回,否则就执行该方法并将结果保存在缓存中

@Cacheable通常搭配三个属性使用

  • value:该属性必须指定,用于表示Cache的名称
  • key:用于指定缓存对应的key,来根据key查询当前Cache中是否存在相key的缓存元素,
  • condition:用于指定当前缓存的触发条件

@CachePut:该注解只是用于将标记该注解的方法的返回值放入缓存中,无论缓存中是否包含当前缓存,属性与 @Cacheable一样

@CacheEvict:该注解用于清除缓存数据,属性除了与 @Cacheable一样的三个属性外还有一个和常用属性

  • allEntries:默认值为false,如果为true将会清除当前名为value值的所有缓存

要使用spring Cache缓存需要在启动类上加入@EnableCaching注解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值