如何解决更新Java请求中给出的字段
我有一个表mytable(a int,b int,c varchar)。 用户可以发送请求
PUT myapi/mytable/{id}
Request body : {'a':1}
PUT myapi/mytable/{id}
Request body : {'b':2}
PUT myapi/mytable/{id}
Request body : {'c':"hello"}
我该如何编写单个通用更新API,该API用给定的“ id”的关联值更新请求中指定的字段,我试图接收该对象并选择了非null字段进行更新,有没有更好的方法?
解决方法
只需使用Apache BeanUtils
将POJO的值复制到您的实体:
BeanUtils.copyProperties(entity,myTable,getNullPropertyNames(entity));
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
copyProperties
方法接受第三个参数作为要忽略的属性名称。
您可以使用ModelMapper
来将不仅非null的映射映射到实体。
public static <T> void merge(T source,T target) {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT).setSkipNullEnabled(true);
modelMapper.map(source,target);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。