对于嵌入参数的GET请求,我有此方法。主要思想是,如果链接包含?embedded = true,它将返回实体,如果不是,则返回DTO对象:
@GetMapping("/todos")
public List<Resource<?>> getAllToDoNote(@RequestParam(value = "embedded",required =false)String embedded){
List<Resource<ToDoNote>> noteResources = new ArrayList<Resource<ToDoNote>>();
List<ToDoNote> allNotes = toDoNoteService.getAllToDoNote();
if(embedded!=null && embedded.equals("true")) {
for(int i=0; i< allNotes.size();i++) {
Resource<ToDoNote> noteResource = new Resource<>(allNotes.get(i));
//Link linkTo = linkTo(methodOn(this.getClass()).getNotesUsers(allNotes.get(i).getId())).withRel("users");
//noteResource.add(linkTo);
noteResources.add(noteResource);
}
//return toDoNoteService.getAllToDoNote();
return noteResources;
}
else {
//System.out.println("embedded " +embedded);
List<Resource<ToDoNoteDTO>> dtoResources = new ArrayList<Resource<ToDoNoteDTO>>();
notes = toDoNoteService.getAllToDoNote();
List<ToDoNoteDTO> noteDtos = new ArrayList<ToDoNoteDTO>();
for(int i=0; i<notes.size(); i++) {
//System.out.println("size" +notes.get(i).getName());
noteDtos.add(convertToDto(notes.get(i)));
}
for(int i=0; i< noteDtos.size();i++) {
Resource<ToDoNoteDTO> dtoResource = new Resource<>(noteDtos.get(i));
Link linkTo = linkTo(methodOn(this.getClass()).getNotesUsers(allNotes.get(i).getId())).withRel("users");
dtoResource.add(linkTo);
dtoResources.add(dtoResource);
}
return dtoResources;
//return null;
}
}
@Validated
public class ToDoNote {
private Integer id;
@NotNull(message = "Name may not be null")
private String name;
@JsonFormat(pattern="yyyy-MM-dd")
private Date dateToComplete;
private String description;
private Integer priority;
private Boolean completed;
private ArrayList<User> users;
....
}
public class ToDoNoteDTO {
private Integer id;
@NotNull(message = "Name may not be null")
private String name;
@JsonFormat(pattern="yyyy-MM-dd")
private Date dateToComplete;
private String description;
private Integer priority;
private Boolean completed;
....
}
但是,我在返回行上遇到错误:
类型不匹配:无法从List
编辑
我已经可以使用资源>而不是列表来使它工作,但是现在有了_embedded属性,经过一番搜索之后,似乎无法删除它。因此,我只想了解一些有关如何处理这种情况的想法,即根据给定的嵌入式参数使用不同的实体进行响应。谢谢。
EDIT2 添加了实体和DTO类。
答案 0 :(得分:0)
如果您想根据用户需要返回不同的字段,我建议使用spring数据剩余预测:请参见https://docs.spring.io/spring-data/rest/docs/current/reference/html/#projections-excerpts