Java P
Java P

Reputation: 2291

Hibernate DTO and value object mapping

Is it good practice to take hibernate entities till presentation layer? or Do we need to map all properties of entities to a value object and value object will be used for UI?

Please let me know advantages and disadvantages of both the appoaches.

When should we use what?

Upvotes: 9

Views: 10638

Answers (2)

Hazhir
Hazhir

Reputation: 788

You may also gain a bit more of performance and RAM usage efficiency if you expose your entities across different layers and modules. it's totally up to you which way to go, but I've never seen enterprise or even middle size application that exposes entities beyond their Data Service project/layer.

Upvotes: 0

Firo
Firo

Reputation: 30813

what you call DTO are entities in ORMs. They are normally part of a domain model which contains business logic and contain most of the time more data than is needed to render individual views. My personal rule of thumb

Use entities in Views when there is no transfer layer between the DAL and the view and there is little business logic:

  • Advantages:
    • one model
    • no need to map between models
    • easier use of lazy loading
  • Disadvantages:
    • each change in the model means change of the views
    • many disadvatages with transfer layer see below

Map entities to DTOs when there is a transfer layer and/or the viewdata differs from entities or aggregate many different entities

  • Advantages:
    • DTOs/ views dont have to change when there are changes to the models
    • avoid sending entities over the wire which has loads of problems (lazy loading exceptions, much unneeded data sent, expose sensible information, ...)
    • Model has fewer responsibilities (serialisation) which make them easier to reuse (eg. backend processing)
  • Disadvantages:
    • more classes to write
    • code to translate entities to DTOs

Upvotes: 13

Related Questions