I'm practicing with the database mongoDB inside a Java project.
I have a Collection "Object" wich holds all documents with information about "objects". These "objects" are represented bij a Class in Java called "LoanboardObject". An Object can be made/changed with an web application that sends the data with a Post message to the Server. The Object is created and the parameters are stored in the object.
LoanBoardObject
public class LoanboardObject implements ILoanBoardEntity {
private ObjectId id;
private String objectName;
private String objectCode;
private String category;
private Boolean lent = false;
private String description = "";
private Boolean enabled = false;
public BasicDBObject toDBObject() {
BasicDBObject object = new BasicDBObject();
object.put("_id", id);
object.put("object_name", objectName);
object.put("object_code", objectCode);
object.put("category", category);
object.put("lent", lent);
object.put("description", description);
object.put("enabled", enabled);
return object;
}
...
}
To save this object to the database I do the following:
NewObjectServlet
//Create the object
LoanboardObject object = new LoanboardObject(objectId, etc...);
//Create the database
MongoDataTx tx = new MongoDataTx(DATABASE);
tx.save(object.toDBObject(), "object");
MongoDataTX
private DB db;
public MongoDataTx(String dbName) {
db = Mongo.getMongoDB().getMongoClient().getDB(dbName);
}
public void save(final DBObject object, String collection) {
DBCollection coll = db.getCollection(collection);
coll.save(object);
}
Mongo
private static final String HOST = "localhost";
private static final int PORT = 27017;
private static Mongo mongoDB;
private static MongoClient mongo;
public Mongo() {
try {
mongo = new MongoClient(HOST, PORT);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public static Mongo getMongoDB() {
if (mongoDB == null) {
mongoDB = new Mongo();
}
return mongoDB;
}
public MongoClient getMongoClient() {
return mongo;
}
The problem with this is when a value is Null, the key-value pair it's still added to the database (but that's not nececary). One way to solve this is to make checks to see if the values aren't Null.
if(id != null){
object.put("_id", id);
}
But is it possible to give mongodb settings so it ignores key-value pairs with the value Null? basicly same as here but than with Java.
Or should i use a function to add these values
something like this
public BasicDBObject toDBObject() {
addElementToObject("_id", id, object);
addElementToObject("object_name", objectName, object);
addElementToObject("object_code", objectCode, object);
addElementToObject("category", category, object);
...
}
private <T> void addElementToObject(String key, T value, BasicDBObject object) {
if (value != null) {
object.put(key, value);
}
}