Method java jpa save data tools
- Since some fields jpa method alone is not updated, Save method may update a data, but has the drawback that it will also update the field is empty up.
If there is a utility class may be a non-empty data entity class findOne jpa mapped onto the data, and then save, it will be a lot easier as follows:
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class UpdateUtil {
/**
* 所有为空值的属性都不copy
*
* @param source
* @param target
*/
public static void copyNullProperties(Object source, Object target) {
BeanUtils.copyProperties(source, target, getNullField(source));
}
/**
* 获取属性中为空的字段
*
* @param target
* @return
*/
private static String[] getNullField(Object target) {
BeanWrapper beanWrapper = new BeanWrapperImpl(target);
PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
Set<String> notNullFieldSet = new HashSet<>();
if (propertyDescriptors.length > 0) {
for (PropertyDescriptor p : propertyDescriptors) {
String name = p.getName();
Object value = beanWrapper.getPropertyValue(name);
if (Objects.isNull(value)) {
notNullFieldSet.add(name);
}
}
}
String[] notNullField = new String[notNullFieldSet.size()];
return notNullFieldSet.toArray(notNullField);
}
public static void main(String[] args) {
IdNameVo newvo= new IdNameVo();
newvo.setId("1");
newvo.setName("更新后的实体类");
newvo.setLevel(1);
newvo.setParentId("0");
IdNameVo old= new IdNameVo();
old.setId("1");
old.setName("更新前的实体类");
old.setLevel(2);
old.setParentId("1");
old.setIdx(4);
old.setCode("123");
System.out.println(old);
UpdateUtil.copyNullProperties(newvo,old);
System.out.println(old);
//然后直接jpa的save(vo2)就可以了
}
}
The resulting output is:
IdNameVo (id = 1, name = entity class before update, the parentId =. 1, Level = 2, IDX =. 4, Children = [], code = 123, coupon = null, couponId = null, PromotionId = null,
promotionType = null , searchType = null)
IdNameVo (ID =. 1, name entity class = updated, parentId = 0, level = 1 , idx = 4, children = [], code = 123, coupon = null, couponId = null, promotionId = null,
promotionType = null, searchType = null)