无法使用root将pageRequest强制转换为可分页

Ali*_*ice 0 java spring-mvc spring-data-jpa

我是Java Spring初学者。我正在创建一个博客项目,其中需要加载5个最新帖子。我遇到了这个问题,我不知道如何解决//忽略我//忽略我///忽略我//忽略我//忽略我//忽略我//忽略我

import java.awt.print.Pageable;
import java.util.List;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

public interface PostRepository extends CrudRepository<Post, Long>{
    @Query("SELECT p FROM Post p LEFT JOIN FETCH p.author ORDER BY p.date DESC")
    List<Post> findLatest5Posts(Pageable pageable);
}
Run Code Online (Sandbox Code Playgroud)

PostServicesImp:

import java.awt.print.Pageable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import havan.blog.demo.models.Post;
import havan.blog.demo.models.PostRepository;

@Service
@Primary
public class PostServicesImpl implements PostServices{
    @Autowired
    private PostRepository postRepo;

    @Override
    public List<Post> findAll() {
        // TODO Auto-generated method stub
        return (List<Post>) this.postRepo.findAll();
    }

    @Override
    public List<Post> findLatest5() {
        // TODO Auto-generated method stub
        return (List<Post>) this.postRepo.findLatest5Posts((Pageable)new PageRequest(0, 5));
    }
Run Code Online (Sandbox Code Playgroud)

家用控制器:

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import havan.blog.demo.models.LoginForm;
import havan.blog.demo.models.Post;
import havan.blog.demo.services.NotiService;
import havan.blog.demo.services.PostServices;
import havan.blog.demo.services.UserService;

@Controller
public class HomeController {

    @Autowired
    private PostServices pServices;

    @RequestMapping(path="/*")
    public String index(Model model){
        List<Post> latest5Posts=pServices.findLatest5();
        model.addAttribute("latest5posts",latest5Posts);

        List<Post> allPosts= pServices.findAll();
        model.addAttribute("allPosts",allPosts);

        return "index";
    }
}
Run Code Online (Sandbox Code Playgroud)

//忽略我//忽略我//忽略我//忽略我//忽略我//忽略我//忽略我

Mar*_*tok 6

已经晚了,但也许可以对其他人有所帮助。

您已经从中导入了Pageable类,java.awt.print.Pageable但是您需要Pageable从Spring的包中引入:org.springframework.data.domain.Pageable