I'm studying Morphia, but confused with the DBRef
1
@Entity
public class Blog {
@Id ObjectId id;
@reference User author;
String content;
}
or
2
@Entity
public class Blog {
@Id ObjectId id;
开发者_StackOverflow中文版 ObjectId authorId;
String content;
}
which one should I choose?
eveytime blogDAO.get(id); the first one every query would load all the User data, can that be very slow or waste time?
I suggest #3 ;) :
@Entity
public class Blog {
@Id ObjectId id;
ObjectId authorId;
...
String firstName;
String lastName;
...
String content;
}
Mongodb good fit for data denormalization, so my opinion is that you need add some user related data to the blog post in order to quick display blog posts list. In case if you need more user info then exists in Blog document (for blog displaying for example) you can load blog first and then user. Also you need update user data within each user blog when he update his profile.
I would suggest something like:
@Entity
public class Blog {
@Id ObjectId id;
@Reference(lazy = true) User author;
As well as having the denormalized fields. This way you have acess to the User object but Morphia will only load it when needed.
Note: you need cglib and proxytools in your classpath for this to work. See: http://code.google.com/p/morphia/wiki/Dependencies
Take a look at this article, http://valyagolev.net/article/mongo_dbref/. It gives some info on DBRefs.
A lot depends on use cases, but really, general rule of thumb is to avoid DBRefs unless absolutely required. If you can get away(make every attempt to do so) with using embedded properties, you should do so.
But if your access patterns are such that you do not really get the item you are referring to with the parent, then you can use simple objectid based references instead of dbref.
精彩评论