Skip to content

Instantly share code, notes, and snippets.

@mmpataki
Last active July 28, 2021 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmpataki/39c259b6fea72f94310e1810c23c112e to your computer and use it in GitHub Desktop.
Save mmpataki/39c259b6fea72f94310e1810c23c112e to your computer and use it in GitHub Desktop.
Updateable Mongo Store
/*
* Model to be stored
*/
public class Dish extends Updateable {
String name;
String originCountry;
String recipe;
public Dish(String name, String originCountry, String recipe) {
this.name = name;
this.originCountry = originCountry;
this.recipe = recipe;
}
/* updates */
public void setName(String name) {
doUpdate("name", this.name, name);
this.name = name;
}
public void setOriginCountry(String originCountry) {
doUpdate("originCountry", this.originCountry, originCountry);
this.originCountry = originCountry;
}
public void setRecipe(String recipe) {
doUpdate("recipe", this.recipe, recipe);
this.recipe = recipe;
}
/* getters */
public String getName() {
return name;
}
public String getOriginCountry() {
return originCountry;
}
public String getRecipe() {
return recipe;
}
@Override
public String toString() {
return "Dish{" +
"name='" + name + '\'' +
", originCountry='" + originCountry + '\'' +
", recipe='" + recipe + '\'' +
", updates=" + updates +
'}';
}
}
public class Main {
public static void main(String[] args) {
UpdateableMongoStore ums = new UpdateableMongoStore();
Dish idli = new Dish("idli", "india", "ask your mom!");
/* save it first time */
ums.save(idli);
/* update it */
idli.setRecipe("mom is not home, get it from a hotel");
ums.save(idli);
}
}
new object
Dish{name='idli', originCountry='india', recipe='ask your mom!', updates={}}
update an object
Dish{name='idli', originCountry='india', recipe='mom is not home, get it from a hotel', updates={recipe=mom is not home, get it from a hotel}}
import java.util.HashMap;
public abstract class Updateable {
public HashMap<String, Object> updates = new HashMap<>();
public void put(String field, Object value) {
updates.put(field, value);
}
public boolean isUpdated() {
return !updates.isEmpty();
}
public HashMap<String, Object> getUpdates() {
return updates;
}
protected void doUpdate(String key, String curVal, String newVal) {
if(!curVal.equals(newVal))
updates.put(key, newVal);
}
}
public class UpdateableMongoStore {
public void save(Updateable updateable) {
if(!updateable.isUpdated()) {
System.out.println("new object");
System.out.println(updateable);
} else {
System.out.println("update an object");
System.out.println(updateable);
/* build some update query using `updateable.getUpdates()` */
/* save them to store */
}
}
/* other store methods */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment