Arjen vd Have
Arjen vd Have

Reputation: 119

Map partial DTO back to Domain object

We have a flex client which we send DTO objects. This is done since our domain object contain a lot of data and the client mostly views just a small portion of the data.

We prefer the DTO's above the lazy loading since a lot of domain objects contain data (in strings) which we do not want to send to the client.

When we make changes to on the client we send the DTO back to the server.

I would like to know the best practices for applying these changes on the domain object and let hibernate save it.

Should i read the domain object first and than copy the values from the DTO to the domain object?

Is there an API which can help me with this so i don't have to create mappers for all my domain objects?

Upvotes: 3

Views: 1736

Answers (2)

Firo
Firo

Reputation: 30813

When you get the DTO back you load the corresponding objects from database and update them according the state of the DTO. Hibernate will take care of change tracking so only changed entities will be saved back to DB.

The reason you want to do it in code is additional logic and validation which are applied when applying changes. For example

  • UserDTO has UserName to show on UI but you do not want to change that easyly right?
  • always validate user input and DTOs coming from the wire is user input

Upvotes: 1

ManuPK
ManuPK

Reputation: 11839

With hibernate it is a best practice to use the DTO as Bean also this should be mapped to a table in DB. Read more about the mapping in hibernate here.This can change if you are using a Legacy database.

Lets say I have 2 Beans User and Address. These will be mapped to the backing tables tUsers and tAddresses. This is the Typicall structure you muse with hibernate. You can call User and Address class a Bean.

Now, Lets say I need a DTO whose data will be filled from a query from multiple tables and it don't have a backing table. There are multiple ways to fill a DTO rather than using a Bean for Data Transfer.

My definitions are arguable, but I feel the first approach(using Bean) is good, regardless you call it DTO or Bean.

Upvotes: 1

Related Questions