How to deal with a two-way @DBref in Spring Data?

481 Views Asked by At

I have a Bike model:

public class Bike {

    @Id
    private ObjectId objectId;

    @DBRef
    private Brand brand;

    private String model;
}

and a Brand model:

public class Brand {

    @Id
    private ObjectId objectId;

    private String name;

    @DBRef
    private List<Bike> bikes;
}

If I use the bikeRepository.findAll() provided by Spring Data, I get into a loop, since bikes makes reference to Brand document, which in turns has references to Bike document.

How to deal with this? I would like to get the bike list with the brand object (or even just the brand name)

1

There are 1 best solutions below

5
On

Try to add an @JsonBackReference annotation to your bike class:

public class Bike {

    @Id
    private ObjectId objectId;

    @JsonBackReference
    @DBRef
    private Brand brand;

    private String model;
}