由于hibernate更新数据时,不想把null的字段给更新到数据库所有这样
有两个方法:
target:数据库查的,source前端传的,会去除所有前端传的为null的字段
beanCopy(T source, T target)
beanCopyWithIngore(T source, T target, String… ignoreProperties) //不复制部分字段的值
beanCopyWithIngore(T source, T target, String… ignoreProperties)
public class BeanCopyUtil {
//source中的非空属性复制到target中
public static void beanCopy(T source, T target) {
BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
}
//source中的非空属性复制到target中,但是忽略指定的属性,也就是说有些属性是不可修改的(个人业务需要)
public static <T> void beanCopyWithIngore(T source, T target, String... ignoreProperties) {
String[] pns = getNullAndIgnorePropertyNames(source, ignoreProperties);
BeanUtils.copyProperties(source, target, pns);
}
public static String[] getNullAndIgnorePropertyNames(Object source, String... ignoreProperties) {
Set<String> emptyNames = getNullPropertyNameSet(source);
for (String s : ignoreProperties) {
emptyNames.add(s);
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
public static String[] getNullPropertyNames(Object source) {
Set<String> emptyNames = getNullPropertyNameSet(source);
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
public static Set<String> getNullPropertyNameSet(Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<>();
for (java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
return emptyNames;
}
@Data
public static class Student{
Long id;
String name;
String schoolName;
String home;
}
public static void main(String[] args) {
/* Student student = new Student();
student.setId(1l);
student.setName("zs");
final BeanWrapper src = new BeanWrapperImpl(student);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<>();
for (java.beans.PropertyDescriptor pd : pds) {
System.out.println(pd.getName());
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
System.out.println(emptyNames);*/
// return emptyNames;
Student target = new Student();
target.setId(1l);
target.setName("张三");
Student source = new Student();
source.setHome("云南");
beanCopy(source,target);
System.out.println(target);
}
}