The easiest way to do it is to implement for each bean you want to persist a kind of mapper that will populate the DBObject adding all the bean's fields you want to persist.
But, what if you would to have something more general ? Well the answer seems to be relatively simple: transform the bean into a Map, then new BasicDBObject(map), done! Ok, have you tried to transform a java bean into a LinkedHashMap ?
If you google for it, you will find tons of java libraries that do all kind of bean to bean mapping, reflection and all sort of bean utils! But nothing really simple like BeanUtils.toMap(bean).
So here a very simple Groovy script that will achieve the task :
def Map toMap(object) { return object?.properties.findAll{ (it.key != 'class') }.collectEntries {
it.value == null || it.value instanceof Serializable ? [it.key, it.value] : [it.key, toMap(it.value)]
}
}
and back to bean :
def toObject(map, obj) {
map.each {
def field = obj.class.getDeclaredField(it.key)
if (it.value != null) {
if (field.getType().equals(it.value.class)){
obj."$it.key" = it.value
}else if (it.value instanceof Map){
def objectFieldValue = obj."$it.key"
def fieldValue = (objectFieldValue == null) ? field.getType().newInstance() : objectFieldValue
obj."$it.key" = toObject(it.value,fieldValue)
}
}
}
return obj;
}
thank you very much for that. works like charm!
ReplyDeletethanks
ReplyDelete