[英]Copy not null and not empty fields from one object to another object of the same type(Objects are same type) in java
I am using hibernate, struts, extjs in my project.我在我的项目中使用hibernate,struts,extjs。
I have a Customer object with these fields:我有一个具有以下字段的客户 object:
custId,
客户编号,
custName, address, phone客户姓名、地址、电话
and in my project from UI side I get an object customer with custName
.在我的 UI 项目中,我得到了一个 object 的
custName
客户。
So I need to update the above object( custName
is unique).所以我需要更新上面的对象(
custName
是唯一的)。 I have only one object with the same customer name.我只有一个 object 具有相同的客户名称。 So I will get that object using customer name (object from DB).
所以我将使用客户名称(来自数据库的对象)获得 object。
Now I have to save the object with the updated customer name.现在我必须用更新后的客户名称保存 object。
If I save as follows I have Customer Object from UI, is cust如果我按如下方式保存,我有来自 UI 的客户 Object,是客户
Customer cust1 = getCustomerByName(cust.getCustName());
客户 cust1 = getCustomerByName(cust.getCustName());
cust.setCustId(cust1.getCustId());
cust.setCustId(cust1.getCustId()); save(cust);
保存(客户);
If I do this I lose the customer address and phone number.如果我这样做,我会丢失客户地址和电话号码。
So, how can I copy one object not null or not empty field values to another object of same type.那么,如何将一个 object 而不是 null 或非空字段值复制到另一个相同类型的 object。
Can any one please help.任何人都可以帮忙。 I just stuck here.
我只是被困在这里。 It's stopping me to save.
它阻止我保存。
Thanks in advance!提前致谢!
You are mixing up your references to cust
and cust1
.您混淆了对
cust
和cust1
的引用。
Unless cust
already had an address, no amount of setting JUST the custId
on cust
would also copy the address from cust1
.除非
cust
已经有一个地址,否则在cust
上仅设置custId
也不会从cust1
复制地址。
Two options.两种选择。 Use reflection to find all fields and copy the ones that are not null. Or better option, write an update method that explicitly checks each field and updates the database instance's fields as appropriate.
使用反射查找所有字段并复制不是 null 的字段。或者更好的选择是编写一个更新方法来显式检查每个字段并根据需要更新数据库实例的字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.