仅在json中返回ID,而不是完整实体对象 [英] Return only ID in json instead full entity object
问题描述
在Spring Boot中从RESTful应用程序创建响应时遇到问题.我的实体包含2个子实体属性.
I have a problem with creating response from my RESTful application in Spring Boot. I have entity which contain 2 subentity properties.
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "attendances")
public class Attendance {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Version
@Column(name = "version")
private long version;
@CreatedDate
@Column(name = "date_created")
private Date dateCreated;
@LastModifiedDate
@Column(name = "last_created")
private Date lastUpdated;
@ManyToOne
@JoinColumn(name = "member_id")
@NotNull
private Member member;
@ManyToOne
@JoinColumn(name = "meeting_id")
@NotNull
private Meeting meeting;
getters, setters..
}
当我使用此数据获取JSON时,我总是会获得具有完整的Member和Meeting实体的完整对象.在这种情况下,我只需要成员ID和会议ID.可以使用特定的注释来做到这一点吗?
When I get JSON with this data, I always get full object with full Member and Meeting entities. In this case, I need only member id and meeting id. Is it possible to do that with a specific annotations?
推荐答案
注释解决方案
可以通过对JSON视图使用批注@JsonView
public class View {
interface Summary {}
}
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "attendances")
public class Attendance {
...
@JsonView(View.Summary.class)
@ManyToOne
@JoinColumn(name = "member_id")
@NotNull
private Member member;
@JsonView(View.Summary.class)
@ManyToOne
@JoinColumn(name = "meeting_id")
@NotNull
private Meeting meeting;
...
}
@RestController
public class ExampleController {
@JsonView(View.Summary.class)
@RequestMapping(...)
public Attendance annotationShowCase() {
Attendance attendance = // retrieve attendance
return attendance;
}
}
因为annotationShowCase()
用@JsonView(View.Summary.class)
进行了注释,所以返回的Attendance
将只公开也用@JsonView(View.Summary.class)
进行注释的字段.
Because annotationShowCase()
is annotated with @JsonView(View.Summary.class)
, the returned Attendance
will only expose the fields also annotated with @JsonView(View.Summary.class)
.
此解决方案使用DTO构造:创建一个新类,用于将某些字段暴露给JSON
This solution uses the DTO construct: create a new class which serves the purpose of exposing certain fields to JSON
public class AttendanceSummary {
private long memberId;
private long meetingId;
public AttendanceSummary(Attendance attendance) {
this.memberId = attendance.getMemberId();
this.meetingId = attendance.getMeetingId();
}
// getters and setters
}
@RestController
public class ExampleController {
@RequestMapping(...)
public AttendanceSummary dtoShowCase() {
Attendance attendance = // retrieve attendance
return new AttendanceSummary(attendance);
}
}
这篇关于仅在json中返回ID,而不是完整实体对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!