我正在使用Hibernate作为ORM和Jackson作为JSON序列化程序的Spring启动应用程序。
我有三个模型对象和所有三个模型的CRUD操作。
Class Student{
private Teacher teacher; // Teacher of the student — to be fetched eagerly
+Getter/Setter
}
class Teacher {
private List<Subject> subject; // List of subjects associated to that user— to be fetched eagerly
+Getter/Setter
}
class Subject {
private long subjectId
//Other subject properties
+ Getter/Setter
}
每当我触发学生信息的获取请求时,我都会获得正确的教师信息,因为我也收到了主题信息,这对我来说是不必要的。在我请求教师信息的同时,我需要主题信息与此相关联。如果我使用@JsonBackReference
作为主题我会一直失去它。我不知道如何实现这一目标。
提前感谢您的帮助!!
答案 0 :(得分:2)
您可以使用JSON Views
来自春季博客:
public class View {
interface Summary {}
}
public class User {
@JsonView(View.Summary.class)
private Long id;
@JsonView(View.Summary.class)
private String firstname;
@JsonView(View.Summary.class)
private String lastname;
private String email;
private String address;
private String postalCode;
private String city;
private String country;
}
public class Message {
@JsonView(View.Summary.class)
private Long id;
@JsonView(View.Summary.class)
private LocalDate created;
@JsonView(View.Summary.class)
private String title;
@JsonView(View.Summary.class)
private User author;
private List<User> recipients;
private String body;
}
并在控制器中
@RestController
public class MessageController {
@Autowired
private MessageService messageService;
@JsonView(View.Summary.class)
@RequestMapping("/")
public List<Message> getAllMessages() {
return messageService.getAll();
}
@RequestMapping("/{id}")
public Message getMessage(@PathVariable Long id) {
return messageService.get(id);
}
}
PS:目前没有链接到http://fasterxml.com/。
答案 1 :(得分:0)
您也可以这样注释
Class Student{
@JsonIgnoreProperties("subject")
private Teacher teacher; // Teacher of the student — to be fetched eagerly
}