Spring Data Jpa 使用Spring Data的RESTful Web服务REST不工作,但使用Spring MVC的RESTful Web服务正在工作

pu3pd22g  于 8个月前  发布在  Spring
关注(0)|答案(1)|浏览(91)

PostRepository.java

package com.example.demo.repository;

import com.example.demo.domain.Post;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import java.util.List;

@RepositoryRestResource(collectionResourceRel = "posts", path = "posts")
public interface PostRepository extends CrudRepository<Post, Long> {
        Post findOneByTitle(@Param("title") String title);
        List<Post> findByBodyContaining(@Param("keyword") String keyword);
        }

PostRestController.java

package com.example.demo.web;

import com.example.demo.domain.Post;
import com.example.demo.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@RestController
public class PostRestController {
    @Autowired
    private final PostRepository postRepository;
    public PostRestController(PostRepository postRepository) {
            this.postRepository = postRepository;
    }
    @RequestMapping(value = "/post/findByTitle")
    public Post findOneByTitle(@RequestParam("title") String title) {
            return postRepository.findOneByTitle(title);
    }
    @RequestMapping(value = "/post/search")
    public List<Post> findByBodyContaining(@RequestParam("keyword") String keyword) {
            return postRepository.findByBodyContaining(keyword);
    }
    @RequestMapping(value = "/post/count")
    public long count() {
            return postRepository.count();
    }
}

下面所有的都在工作

http://localhost:8080/ 
 http://localhost:8080/h2-console 
 http://localhost:8080/post/search?keyword=Geeky
 http://localhost:8080/post/findByTitle?title=Youtube

http://localhost:8080/posts不工作(404错误)
我只是想学习Spring,我知道应该遵循最近的指南,但开始这一个,我已经坐在这3天,首先是javax到jakecraft名称的变化,造成了巨大的问题,然后这一个@RepositoryRestResource(collectionResourceRel = "posts", path = "posts")似乎是不工作,一直在寻找解决方案,在过去的3个小时,但似乎没有工作

hs1ihplo

hs1ihplo1#

要解决这个问题,您可以考虑从PostRepository中删除@RepositoryRestResource注解,或者更改PostRestController中findByTitle方法的@RequestMapping注解中的路径。确保没有可能导致此问题的冲突Map。

相关问题