Spring Data Mongo MongoDB DBRef lazy initialization

Lombardo picture Lombardo · Feb 20, 2015 · Viewed 8.6k times · Source

I'm using Spring + Spring Data MongoDB. My model is like this:

@Document(collection = "actors")
public class Actor extends DomainEntity {

private String name;
private String surname;
@DBRef(lazy = true)
private List<Class> classes;

The other class is pretty generic, so I don't post it. My problem is that the list "classes" isn't loaded when i try to access it, the attribute remains being some kind of proxy object. Example:

Actor a = actorRepository.findOne(id);
//At this moment classes are a proxy object because of the lazy

//Now I try to load the reference and nothing works
a.getClasses();
a.getClasses().size();
a.getClases().get(0).getAttr();
for(Class g:a.getClasses()){
        g.getAttr();
    }

I considered a ton of options, but no way to make it working...

Answer

Douglas picture Douglas · Aug 1, 2015

I'm using spring-data-mongodb-1.7.0.RELEASE and I was able to solve this issue by initializing the lazy-loaded collection in its declaration, for instance:

@DBRef(lazy = true)
private List<Class> classes = new ArrayList<>();