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();
}
}
All of the below are working
http://localhost:8080/
http://localhost:8080/h2-console
http://localhost:8080/post/search?keyword=Geeky
http://localhost:8080/post/findByTitle?title=Youtube
But http://localhost:8080/posts is not working (404 error)
I just wanted to learn spring and I know should follow recent guides, but started this one and I've been sitting with this for 3 days, first was javax to jakarta name change that caused huge problem and then this one where @RepositoryRestResource(collectionResourceRel = "posts", path = "posts") seems to be not working, have been looking into solutions for the past 3 hours but nothing seems to work
To resolve this, you could consider either removing the @RepositoryRestResource annotation from the PostRepository or changing the path in the @RequestMapping annotation for the findByTitle method in PostRestController. Make sure there's no conflicting mapping that could be causing the issue.