Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Mongo MongoDB DBRef lazy initialization

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...

like image 661
Lombardo Avatar asked Sep 28 '22 17:09

Lombardo


1 Answers

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<>();
like image 51
Douglas Avatar answered Oct 13 '22 12:10

Douglas