Spring Mongo DB @DBRef(lazy=true) - How to lazy Load

4.1k Views Asked by At

I have a model like the one below (assume as pseudo code )

class Student {

   @Id
   private String id;
   private String firstname;
   .....;

   @DBRef(lazy=true)
   private College college     

   // getters and setters

}

class College {

  @Id
  private String id;
  private String name;
  // other attributes.
  // getters and setters

}

I am using @DBRef(lazy=true) so that I do not load the college associated with the student. For example: if I have a repository method for Student called findByFirstname(String firstname), I can load the student without the college. However, at times I would also want to load the student with college. Is it possible to write a repository method with a custom query using the @Query annotation (org.springframework.data.mongodb.core.query.Query) where I can load the student (all fields) and also the associated college instance ?

@Query( what should go here ?) 
Student findStudentWithCollege(String firstname)

If no, then what would be a suggested way to load lazy documents on demand ?

As per the documentation

"DBRefs can also be resolved lazily. In this case the actual Object or Collection of references is resolved on first access of the property. Use the lazy attribute of @DBRef to specify this. Required properties that are also defined as lazy loading DBRef and used as constructor arguments are also decorated with the lazy loading proxy making sure to put as little pressure on the database and network as possible." I guess this may not be suitable for cases where one would want to load a student whose last name is "Smith" along with the college instance for each of the students retrieved.

0

There are 0 best solutions below