开发者

Morphia and MongoDB - Modeling Something like Settings

开发者 https://www.devze.com 2023-01-23 18:07 出处:网络
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

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));
0

精彩评论

暂无评论...
验证码 换一张
取 消