0

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)

Sebastian M
  • 471
  • 1
  • 4
  • 20

1 Answers1

0

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;
}
Dilara Daria
  • 63
  • 1
  • 7
  • I tried this, and even though that makes the query work a bit faster, it is still extremely slow. When I had a String as a brand instead of a Brand object the query executed in less than 2 seconds. Now, with the same amount of bikes, it takes somewhere between 12 and 15 seconds – Sebastian M Sep 16 '20 at 19:04
  • @SebastianM Well your original question only asked about the loop problem. How do you keep your documents on MongoDB? – Dilara Daria Sep 17 '20 at 06:18
  • What do you mean with how? – Sebastian M Sep 17 '20 at 08:13
  • @SebastianM As in do you hold ObjectId 's of bikes in Brand? And the objectID of brand in bike? – Dilara Daria Sep 17 '20 at 12:01
  • Yes, that is how I keep my documents. I pasted my code in the original post for reference. – Sebastian M Sep 22 '20 at 20:16