Return only ID in json instead full entity object

Solution by 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).

Solution by DTO

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);
    }
}

Tags:

Spring