简体   繁体   中英

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.

I have a Customer object with these fields:

custId,
custName, address, phone

and in my project from UI side I get an object customer with custName .

So I need to update the above object( custName is unique). I have only one object with the same customer name. So I will get that object using customer name (object from DB).

Now I have to save the object with the updated customer name.

If I save as follows I have Customer Object from UI, is cust

Customer cust1 = getCustomerByName(cust.getCustName());

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.

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 .

Unless cust already had an address, no amount of setting JUST the custId on cust would also copy the address from 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM