X-editable 插件和 Spring MVC - 更新实体的最佳方式

X-editable plugin and Spring MVC - best way to update Entity

堆栈搜索但未找到答案。我有几个文本字段的子页面,当我编辑数据字段时,插件会向我的控制器发送回复:

@RequestMapping(value = "/myAcc", method = RequestMethod.POST)
    public String getValues(@ModelAttribute XEditableForm form){
        userService.update(form.getPk(), form.getValue());
        return "myAcc";
    }

其中 userService 在数据库中进行用户更新

@Transactional
public void update(long id, String firstName){
    User user= userRepository.findOne(id);
    user.setFirstName(firstName);
    userRepository.save(user);
}

问题是每次在这个方法中我都会检查从 xeditable 插件返回的内容并更新特定的用户字段,即姓氏等。在我看来这不是最好的解决方案。

XEditableForm returns:

pk - primary key of record to be updated (ID in db) 
name - name of field to be updated (column in db) 
value - new value

你的问题。我怎样才能做得更好?

我会自己回答的。在这种情况下,我们可以使用

org.springframework.utilClass ReflectionUtils

使用示例:

User user = userRepository.findOne(id);  
Field name = ReflectionUtils.findField(User.class, "name"); 
ReflectionUtils.makeAccessible(true);  
name.set(user, "Admin");

通过这种方式,您可以编辑 class 中知道其名称的字段。这就是我的意思。