I have a controller that is supposed to update any object in the database, how can I make it so that that objects setters are called based on the property keys of that object?
I have heard that reflection might be the answer to my prays, is that so, and if so, what is the most elegant way to achieve what I’m looking for?
Object entity = repository.findOne(id);
for (Object key : request.getParameterMap().keySet()) {
//invoke setter-method of entity
//for example, if key == "name" , i want entity.setName() to be called
}
repository.save(entity)
I’m running Spring MVC. If more info is needed please let me know!
UPDATE, working code:
Object entity = repository.findOne(id);
BeanWrapper beanWrapper = new BeanWrapperImpl(entity);
for (Object key : request.getParameterMap().keySet()) {
beanWrapper.setPropertyValue(key.toString(), request.getParameterMap().get(key));
}
repository.save(entity);
Perhaps it would be better to the same data binding facilities that Spring MVC uses to implement
@ModelAttribute, etc.Note that this approach imposes specific format of parameter names, as described in 5.4 Bean manipulation and the BeanWrapper.