I'm evaluating MongoDB and Morphia right now. How would I model something like 'settings', where there is only one 'record' (I'm not sure of the proper Mongo term to use). Must I override the save method in my entity class? An example of how to do this and how t开发者_开发知识库o use it would be awesome.
For example, I'd like to store the home page configuration:
home page settings
show friends list: false
marketing text: "You'll love it here"
main image: main.jpg
If you basically only want a single copy of settings for your application (like a singleton) then I would suggest something like this:
@Entity
class Settings {
@Id int id = 0;
boolean showFriendsList = false;
String marketingText = "You'll love it";
byte[] mainImage = ...;
}
Since the id is set to a single value then when you call save it will always update the single entity. If you call insert, and there is already one there, you will get an error (if you are checking for errors).
You can update the entity using get/change/save or update semantics.
Datastore ds = ...;
//get/change/save
Settings s = ds.find(Settings.class).get(); //like findOne in the shell/driver
s.showFriendsList = true;
ds.save(s);
//or update
ds.updateFirst(ds.find(Settings.class), ds.creatUpdateOperations(Settings.class).set("showFiendsList", true));
精彩评论