我正在尝试做一些我认为应该非常简单的事情.我有一个Question对象,设置有spring-boot,spring-data-rest和spring-hateoas.所有的基础工作都很好.我想添加一个自定义控制器,它返回一个List<Question>与我Repository的/questions网址完全相同的格式,以便两者之间的响应兼容.
这是我的控制器:
@Controller
public class QuestionListController {
@Autowired private QuestionRepository questionRepository;
@Autowired private PagedResourcesAssembler<Question> pagedResourcesAssembler;
@Autowired private QuestionResourceAssembler questionResourceAssembler;
@RequestMapping(
value = "/api/questions/filter", method = RequestMethod.GET,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody PagedResources<QuestionResource> filter(
@RequestParam(value = "filter", required = false) String filter,
Pageable p) {
// Using queryDSL here to get a paged list of Questions
Page<Question> page =
questionRepository.findAll(
QuestionPredicate.findWithFilter(filter), p);
// Option 1 - default resource assembler
return …Run Code Online (Sandbox Code Playgroud) spring spring-mvc spring-data spring-data-rest spring-hateoas
什么是典型的用例代码,显示这两个注释之间的区别 - 意味着@RestController和@RepositoryRestController- ?
spring-mvc spring-data spring-data-rest spring-restcontroller
如何正确公开延迟加载的多个字段,以便用户在Spring Data REST中可以GET/ PATCH/ POST/ DELETE多个实体关系?
例如,给定一个由多对多关系绑定的Student实体和Teacher实体,使用以下POJO:
@Entity
public class Teacher { // owner of bidirectional relationship
@Id
private int id;
private String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "teacher_student",
joinColumns = @JoinColumn(name = "teacher_id"),
inverseJoinColumns = @JoinColumn(name = "student_id"))
private Set<Student> students;
// Constructor, getters/setters...
}
@Entity
public class Student {
@Id
private int id;
private String name;
@ManyToMany(mappedBy = "students", fetch = FetchType.LAZY)
private Set<Teacher> …Run Code Online (Sandbox Code Playgroud) 在我们的应用程序中提供以下工作存储库:
public interface PersonRepository extends PagingAndSortingRepository<Person, Integer> {
}
Run Code Online (Sandbox Code Playgroud)
该存储库通过带有URI“ / api / persons”的spring-data-rest公开,并且可以正常工作。
现在,我们想在RestController的方法中重写存储库的后方法:
@RestController
@RequestMapping("/persons")
public class PersonController {
@RequestMapping(value = "/**", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> savePerson(@RequestBody Person person) {
//do something fancy
return "it works";
}
Run Code Online (Sandbox Code Playgroud)
如果我们将数据发布到“ / api / persons”,则将调用PersonController的方法,但是PersonRepository的任何方法(例如GET)都无法通过rest访问。我们不断收到405错误和以下异常:
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
Run Code Online (Sandbox Code Playgroud)
经过一番摸索之后,我们发现,如果我们将@RequestMapping批注的值属性更改为:
value="/**"
Run Code Online (Sandbox Code Playgroud)
至
value="/save"
Run Code Online (Sandbox Code Playgroud)
阅读此问题和链接的文档后,如果值属性为“ / **”,则它也应该起作用