我的目标是将一个对象的字段复制到另一个对象中,但只复制那些非空的对象.我不想明确指定它.更通用的解决方案非常有用且易于维护,即在REST API中实现PATCH,您只允许提供特定字段.
我看到了这个类似的线程,我正在尝试从这里实现一些想法:Helper,以便将非null属性从对象复制到另一个?(JAVA)
但是程序执行后对象不会以任何方式改变.
所以这是我创建的示例类,例如:
class Person {
String name;
int age;
Pet friend;
public Person() {
}
public Person(String name, int age, Pet friend) {
this.name = name;
this.age = age;
this.friend = friend;
}
// getters and setters here
}
class Pet {
String name;
int age;
public Pet(String name, int age) {
this.name = name;
this.age = age;
}
// getters and setters here
}
Run Code Online (Sandbox Code Playgroud)
这是我重写的copyProperty方法:
import org.apache.commons.beanutils.BeanUtilsBean;
import java.lang.reflect.InvocationTargetException;
public class MyBeansUtil extends BeanUtilsBean { …Run Code Online (Sandbox Code Playgroud) 我绝对没有找到完全自动进行部分更新的明确方法(可以通过比较数据库和部分对象中的逐字段对象来实现)。
我看到了一些类似的曲目:
MapperServiceheavyResourceRepository哪种save(Map<String, Object> updates, String id)方法的存储库类型是什么copyProperty方法谢谢您,可以使用PATCH方法,但是我看不到实现它的明确方法。
有这个:
public class Parent {
private String name;
private int age;
private Date birthDate;
private Work work;
static class Work{
private int years;
private String employer;
}
// getters and setters
public static void main(String[] args) {
Parent c = new Parent;
c.setAge(55)
Work work=new Parent.Work();
work.setEmployer("Example");
c.setWork(work);
//save c in a DB...
}
}
Run Code Online (Sandbox Code Playgroud)
我只想使用反射复制非空属性。该方法在这里描述与BeanUtils的作品非常好,但它会将所有没有空包装的对象,而不仅仅是没有空字段值:
//fetch c from the db...
Parent sameParent= new Parent;
sameParent.setWork(new Parent.Work());
//Directly from /sf/ask/91118821/#answer-3521314
BeanUtilsBean notNull=new NullAwareBeanUtilsBean();
notNull.copyProperties(c, sameParent);
Run Code Online (Sandbox Code Playgroud)
现在, …
java ×2
hibernate ×1
http-method ×1
javabeans ×1
rest ×1
spring ×1
spring-boot ×1
spring-rest ×1