Abu Sulaiman
Abu Sulaiman

Reputation: 1507

How to swap @JsonBackReference and @JsonManagedReference based on which Entity is reference

I'm trying to find a way to swap the @JsonBackRefence and the @JsonManagedReference based on what entity I reference from the associated repository.

Site.java

@Entity
@Table(name = "Site")
public class Site {

    @Id
    private String id;

    @OneToMany(mappedBy="site")
    @JsonManagedReference
    private List<Building> buildings;
}

Building.java

@Entity
@Table(name = "building")
public class Building{

    @Id
    private String id;

    @ManyToOne
    @JoinColumn(name = "SITE_ID")
    @JsonBackReference
    private Site site;
}

SiteRepository.java

public List<Site> findAll(); //Works as intended

BuildingRepository.java

public Building findById(buildingId); //Works if references are swapped

However when calling findById(buildingId), I want to have the @JsonBackReference swapped. Therefore, the @JsonBackReference is in Site.java and the @JsonManagedReference is in the Building.java entity.

Note: @JsonIdentityInfo almosts handles it, but it gives me too much information ie: when I call findById(buildingId) from the BuildingRepository it gives me all the buildings for the site joined to the building found.

Upvotes: 1

Views: 1324

Answers (1)

Cepr0
Cepr0

Reputation: 30474

If I understand you correctly the @JsonIgnoreProperties annotation should help you:

@JsonIgnoreProperties("site")
@OneToMany(mappedBy="site")
private List<Building> buildings;

@JsonIgnoreProperties("buildings")
@ManyToOne
private Site site;

Upvotes: 5

Related Questions