Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Morphia and MongoDB - Modeling Something like Settings

Tags:

java

mongodb

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 to 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
like image 565
Bradford Avatar asked Nov 30 '25 17:11

Bradford


1 Answers

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));
like image 120
Scott Hernandez Avatar answered Dec 03 '25 08:12

Scott Hernandez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!