Sharad Yadav
Sharad Yadav

Reputation: 3061

Update table for only changed fields

I have a person table and Person.java which maps to the table. I have an edit ui to change details of a Person record. On the edit page user normally changes 1 or 2 fields at a time. I am using AJAX to send the update call and want to only send the fields which are changed. Currently sending the whole object back.

The problem is at the backend about how to update database for only the changed fields.

The UI layer creates a Person object with only the changed fields and rest of the fields will be uninitialized. The object is then passed to DAO for persistence. How the DAO would know what fields are changed? What fields are uninitialized or deliberately set to null for update. Currently the whole object comes so I update all the columns.

Upvotes: 0

Views: 4593

Answers (2)

Oscar
Oscar

Reputation: 1387

What I usually do it's to get first the object with all its fields from the database. Then I update the field that I want and then I send it back to the DAO. The DAO updates the whole object no matter what. Doing it in this way the DAO does not care which one was changed. There are some special cases though where you might want to add another DAO method.

Upvotes: 1

yogi
yogi

Reputation: 11

if you are using ORM (Hibernate) for persistence then you can use hibernate.merge to do a selective update.

Approach for JDBC: Keep the object in session which is used to fill the UI with the initial values that the user can edit. When user submit the changes, compare the submitted values with the object in session and add to a map that contain field name and new value. Use this map to create the update query dynamically.

Upvotes: 1

Related Questions