Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return only ID in json instead full entity object

Tags:

spring

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?

like image 956
Algeroth Avatar asked Dec 22 '17 23:12

Algeroth


1 Answers

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);
    }
}
like image 82
Sync Avatar answered Oct 10 '22 23:10

Sync