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..
}
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?
It is possible by using the annotation for JSON views @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;
}
}
Because annotationShowCase()
is annotated with @JsonView(View.Summary.class)
, the returned Attendance
will only expose the fields also annotated with @JsonView(View.Summary.class)
.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With