what is a good pattern for converting between hibernate entities and data transfer objects?

D Parsin picture D Parsin · Dec 29, 2010 · Viewed 19.7k times · Source

I have had similar questions and concerns as to how to convert between Hibernate entities and data transfer objects to be returned by a web service as are discussed in this question:

Is using data transfer objects in ejb3 considered best practice

One of the factors mentioned here is that if the domain model changes, a set of DTOs will protect consumers in the case of a web service.

Even though it seems like it will add a substantial amount of code to my project, this reasoning seems sound.

Is there a good design pattern that I can use to convert a Hibernate entity (which implements an interface) to a DTO that implements the same interface?

So assuming both of the following implement 'Book', I would need to convert a BookEntity.class to a BookDTO.class so that I can let JAXB serialize and return.

Again, this whole prospect seems dubious to me, but if there are good patterns out there for helping to deal with this conversion, I would love to get some insight.

Is there perhaps some interesting way to convert via reflection? Or a 'builder' pattern that I'm not thinking of?

Should I just ignore the DTO pattern and pass entities around?

Answer

duffymo picture duffymo · Dec 29, 2010

Should I just ignore the DTO pattern and pass entities around?

My preference is usually "yes". I don't like the idea of parallel hierarchies created just for the sake of architectural or layer purity.

The original reason for the DTO pattern was excessive chattiness in EJB 1.0 and 2.0 apps when passing entity EJBs to the view tier. The solution was to put the entity bean state into a DTO.

Another reason that's usually given for creating DTOs is to prohibit modification by the view layer. DTOs are immutable objects in that case, with no behavior. They do nothing but ferry data to the view layer.

I would argue that DTO is a Core J2EE pattern that's become an anti-pattern.

I realize that some people would disagree. I'm simply offering my opinion. It's not the only way to do it, nor necessarily the "right" way. It's my preference.