Blog

JPA implementation patterns: Service Facades and Data Transfers Objects

11 May, 2009

In my previous blog on JPA implementation patterns, I touched upon the subject of the DTO and Service Facade patterns. In this blog I will explore why we would even need such patterns and put these patterns and the DAO pattern into the broader context of JPA application architecture.
If there is one thing that I learned when implementing JPA for the first time is that some of the “old school” enterprise application architecture patterns still apply, even though some people have proclaimed them to be no longer necessary:

  • The DAO has been declared dead because you might just as well invoke the EntityManager directly. It provides a nice enough interface and switching from JPA to a different persistence implementation is not something the DAO abstraction would make much easier.
  • DTO’s have been deemed superfluous because you can also use your domain objects directly in the presentation layer. This is made possible by a combination of the open EntityManager in view pattern, tag libraries to display your domain objects in JSP’s and data-binding utilities to map HTTP request parameters back to domain objects.
  • And finally Service Facades also seem to have gone out of fashion. Instead you can have the controller directly invoke the services it needs or, even simpler, directly contain the business logic.


The resulting application architecture will look something like this diagram of the Spring Web MVC application architecture:
Spring Web MVC application architecture

So why bother with DAO’s, DTO’s and Service Facades?

I’ve already argued why the DAO pattern is still relevant in JPA application architecture. A similar argument can be made for the DTO and Service Facade patterns. While the DTO-less and Service Facade-less architecture displayed above works quite well for straight forward web applications, it has two major drawbacks:

  • If you wish to expose your application to other non-HTML clients (think of web services using SOAP, Flex frontends using AMF or Ajax applications using JSON), you will need a more clearly defined interface. That interface specifies which services get exposed to the client and what types are used as the input and output. Service Facades and DTO’s respectively help you define this interface.
  • Using domain objects directly in the presentation layer requires those domain objects to expose all their fields as public properties with getters and setters. If the fields are not exposed as such, the tag libraries won’t be able to render them and the data binding code won’t be able to set them. As Allen Holub has already argued before, getters and setters are evil. (BTW, some people interpret Holub’s article as an excuse to make all fields public. The article is saying that public getters and setters are no better, but that does not mean your code should just have public fields. Instead the article is advocating use of the tell, don’t ask approach to OO.)

In fact the reason I found out why Service Facades and DTO’s are still useful, is that the application my team and I are developing has a Flex frontend and a command-line interface that communicate to the core using AMF and Hessian respectively. The only HTML code our application produces loads the SWF file for the Flex frontend! We started out without DAO’s, DTO’s and Service Facades as one would do, but added them all to our architecture to make this work. And we got a well defined interface between the service layer and the presentation layer as an added bonus.

Pros and cons of DTO’s

Of course it would be silly to say you should always use DTO’s in your architecture. As always it depends. 🙂 To allow you to make up your own mind, I will list a number of pros and cons of using DTO’s:

  • Con: DTO’s cause code duplication. This is especially the case when your DTO’s have exactly the same fields as your domain objects, and even more so when they both have getters and setters for those fields. But having DTO’s in your architecture allows you to get rid of the getters and setters in your domain objects.
  • Con: DTO’s require you to write boilerplate code to copy properties back and forth. Some people have suggested using a Java Bean mapper framework such as Dozer, Apache Commons BeanUtils, or the Spring Framework’s BeanUtils class, but that requires you add getters and setters to your beans and we just decided we did not want to do that anymore!
  • Pro/Con: DTO’s make it impossible to use EntityManger.merge to copy their state to your persistent objects. Instead you’ll have to apply the DIY merge pattern as described in my blog on saving (detached) entities. Of course forcing you to do something a particular way, and one that is not 100% satisfying, is not really an advantage. But at least the DTO and the DIY merge work well together.
  • Pro: DTO’s ensure you are not hit by unexpected lazy loading problems in your presentation layer. Or in the case of remote invocations they protect you from lazy loading problems when serializing for transport or, even stranger, on the client.
  • Pro: The DTO pattern forces you to think about the interface of your application. You can make your DTO’s richer than your plain domain objects, e.g. by adding security information to them. Or you can group information from multiple domain objects into one DTO to make the interface easier to use.

Before we move on to discuss Service Facades, it might be worth to have a look at Anirudh Vyas’s blog on common abuses of the DTO pattern.

Pros and cons of Service Facades

Just like is the case with DTO’s, there are cases when Service Facades make a lot of sense and there are cases when they just add meaningless overhead. Let’s have a look at some pros and cons:

  • Con: Service Facades add an extra layer that does not do much apart from delegate to the actual service. This argument appeals especially to Java EE developers that have bad memories of the EJB 1.0 based multi-tier architectures we set up in the beginning of this century. 😉
  • Pro: Service Facades can (should!) be made responsible for mapping from DTO’s to domain objects and back. Service Facades are invoked with DTO’s as arguments, map them to domain objects, invoke the actual service (or services), map the result back to DTO’s and return those DTO’s to the client. Actually, to make sure your Service Facades only adhere to Single Responsibility Principle, you should factor the mapping logic out to separate DTO2DOMapper and DO2DTOMapper classes.
  • Pro: Service Facades can function as the transaction boundary of your application, i.e. a transaction is started for the duration of a request to the Service Facade. Instead of having to define the transaction attributes of all your services, you can assume that all service invocation arrive through the Service Facade. Actually, setting your Service Facade to be the transaction boundary is obligatory when you want to invoke more than one service during the handling of one request or when you want the Service Facade to map lazily loaded domain objects to DTO’s. In that case you end with something akin to the open EntityManager in view pattern; a transaction is started that lasts from the moment the incoming DTO’s are translated to domain objects to the moment the resulting DTO’s are returned to the client. (BTW, if you want to enforce that all services invocations go through the Service Facade you can set their transaction attribute to MANDATORY. If a transaction hasn’t already been started when such a service is invoked, an exception is thrown)
  • Pro: The Service Facade pattern forces you to think about the interface of your application. Instead of letting the client invoke all your services, you get to decide which ones to actually expose.

Hmm, I can’t seem to think of many disadvantages to the Service Facade pattern. 😉 Apart from the “overhead” argument and that is a subjective thing. Feel free to add more cons of this pattern to the comment section!

Impact on application architecture

If we apply the DAO, DTO and Service Facade patterns, we end up with a JPA application architecture that looks like this:
application_architecture_with_dtos_and_service_facade
When a request is made, the sequence of events goes something like this:

  1. A service client sends a request to the service facade. All objects sent are DTO’s.
  2. A transaction is started.
  3. The service facade invokes the DTO2DOMapper to map the incoming DTO’s to domain objects. The DTO2DOMapper may invoke one or more DAO’s to load domain objects from the database.
  4. The service facade invokes one or more services to perform actual business logic.
  5. The service facade passes the return values to the DO2DTOMapper and gets DTO’s back. The DO2DTOMapper may invoke one or more services or DAO’s to enrich the DTO’s.
  6. The transaction is committed. Or rolled back in case an exception has occurred.
  7. The service facade passes the DTO’s to client.
  8. The service client receives the DTO’s.

In fact, if you take this diagram and replace “DTO2DOMapper” with “Data binding”, “DO2DTOMapper” with “View rendering”, and “Service Facade” with “Front Controller”, you get the original Web MVC architecture we started out with. The big difference is that the incoming “DTO’s” are request parameters while the outgoing “DTO’s” are HTML:
application_architecture_with_dispatcher_servlet
That makes this blog come full circle, so now is a good time to wrap up. 🙂 As you can see there is no clear-cut answer to whether or not to use DTO’s and Service Facades. It all depends on what you are trying to achieve with your application, for example:

  • Will it be a straight HTML application or will you want to expose it over different protocols?
  • How tightly coupled do you want your clients and your services to be?
  • Do you want your domain objects to not have any getters and setters?

I am very interested to hear what you guys think about the validity of these patterns in modern Java EE architecture. When would you apply then? Or when not and why not? See you all at the next blog in which I will try and tackle the subject of how to handle inheritance in JPA.
P.S. Last week I gave a presentation on this subject to the guys at info.nl and they provided me with some interesting feedback that helped shape this blog. Thanks for that guys!
For a list of all the JPA implementation pattern blogs, please refer to the JPA implementation patterns wrap-up.

guest
25 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Erik Rozendaal
Erik Rozendaal
13 years ago

A long blog post and this reply should probably be as long, but I’ll try to keep it short.
First of all I before you go down the path of DTOs you need to decide what your domain model is like: a data structure or an object model (see chapter 6 of Clean Code for a good explanation)
In case of a data structure (objects with little behavior and all fields exposed through public accessors) you can simply let you domain model be your DTO layer as well. Just use detached entities with merges, etc. To avoid lazy initialization problems you can let the client decide which associations should be eagerly loaded. For example, a client could just send EJB QL queries to the back-end or you could use Query objects. This will work well for CRUD-like applications, admin UIs, etc. I suggest using Grails or a similar framework when you build these kind of applications.
When your domain has complicated transactional behavior you probably want to use an object model instead of a data structure. In this case your object model needs to be fully encapsulated by the service facade provided to clients. Otherwise too many implementation details will leak out, breaking encapsulation.
Because you no longer use your domain model directly in your clients, your service facade interface is no longer directly tied to your domain model. The design can now be optimized for your clients. Clients will need two main types of operations: commands and queries.
Queries can return query result that consist of only simple immutable objects. Final fields and no setters. Query result objects can be created on the the server-side by loading entities and then mapping properties (like the DO2DTOMapper) or directly from EJB QL. In the latter case there is little or no need for getters on your domain objects.
Commands will require the parameters needed to execute transactional behavior in the domain model. An example would be “changeCustomerAddress(VersionedId customerId, Address address)”. Much cleaner than a generic “updateCustomer(CustomerDTO data)”. Command parameters can usually be simple immutable objects. This gives you a very clean interface with no hidden surprises.
Commands are executed by loading the responsible domain object and invoking the right behavior. In general the interaction between your service facade and domain model should be no more complicated than that! This ensures behavior stays within your domain and your service facade will concern itself with transactions, mapping, etc. Not with business logic.
Both command parameters and query results can also be DTOs, but only if you need remoting and without the setters! This is now an implementation detail, not a core design decision of your application.
Finally, if you need to bind to objects in your UI for editing, use form backing objects.
Note that big applications may actually have multiple domain models. Each of these could be an object model (for example the transactional parts) or a data structure (for administrative UIs, etc). Don’t try to use the same solution for these separate models. Especially avoid using a hybrid model within one domain model!

Thomas Vanstals
Thomas Vanstals
13 years ago

Very good article !
We face the same kind of problems 2 years ago when we started developing the client side of our webapp with Flex. We introduce an architecture very similar to yours. We develop a Service Facade on top of our Services. Dozer was in charge of the DTA DO mapping.

Fernando Boaglio
13 years ago

Great job Vincent!
We have a similar architecture here, but using Apache BeanUtils was a real pain, I don’t recommend to use it with recursive copy .

Edgar Vonk
13 years ago

Great article and thanks for coming over to talk to us at Info.nl!
A question on DTO’s: how do you deal with associations in DTO’s? When you decouple the persistence context from the service clients you also loose the ability to perform lazy loading of associations. I think you need to know quite a lot about how the service layer is going to interact with your system (what association data it needs at what point) before you can create a good DTO layer?
Another thing. I am no expert in Seam but I understand they solve this ‘association fetching problem’ in a different way. From Seam and Object/Relational Mapping:
“The solution comes in two parts:
* use an extended persistence context that is scoped to the conversation, instead of to the transaction
* use two transactions per request; the first spans the beginning of the update model values phase until the end of the invoke application phase; the second spans the render response phase ”
Any thoughts on the Seam solution?

trackback

[…] Service Facades and Data Transfers Objects […]

Alex Omilian
Alex Omilian
12 years ago

I would add one more item to the list of Service Façade “cons”; effort (cost). Using a framework like Seam it is very easy to use Entity objects as backing beans for web based screens. This “seamless” architecture discourages the use of distinct application layers such as the Service Façade, and in my experience it certainly does reduce the effort required to get a moderately complex application up and running.
I think it is perfectly valid not to build a Session Façade, so long as we remain mindful of the fact that there will be a cost associated with the refactoring effort required to move to a Service Façade should the need arise (and it often won’t).

Varun Mehta
12 years ago

Dude, looks like you expressed the same thoughts I did a few months back.
http://damroo.blogspot.com/2009/02/2-dto-or-not-2-dto.html

Simon Massey
Simon Massey
12 years ago

I feel that it is the “alien nature” of the your client tier which makes DTOs a preferable solution for you. To explain what I mean we use of the ZK RIA framework as our client and that is a good fit with the Exposed Domain Model pattern. With that framework you keep detached entities as the application model bound to the desktop for re-use with multiple AJAX requests. The “commands” to manipulate them are directly modeled as Java UI Events that are fired into your UI controllers. The UI controllers then manipulated your entities and pass them to the service façade to have them merged and manipulated by application services. Only UI mapped entity fields are exposed to the browser so you don’t have to have the security concerns. I wrote an article with some sample code (with no façade) here:
http://java.dzone.com/articles/using-desktop-model-view
With such an Exposed Domain Model approach you can either go with Open Session In View or you have to figure out how scope the transaction to a narrower scope. For scalability we prefer to scope the database transaction to a business façade. More or less the façade encapsulates the use case for the UI controller and needs to ensure that enough of the entities are loaded for rendering. The façade can re-attach the detached entities, and use queries to load more data, and merge the detached entities. The UI controller is responsible for replacing the merged entity returned from the façade into the UI model mapped to the browser screen.
If we wanted to add a new client, say some soap over jms remote system, then we would also a façade. That would load data from the xml payload (which can be considered as an xml-ised DTO), load the referenced domain entities, map the xml-dto to a new/updated entity, perform validation of the ‘command’ represented in the message, all within a transaction. The façade would re-use internal application services just like the façades for our ‘native’ AJAX front-end.
I must say I was keen to ditch the façades a while ago as they give a procedural “transaction script pattern” smell that plagued early EJB. Certainly in a small app they look like over-kill. Yet they perform a clear responsibility, particularly if we let then go straight to the DOAs occasionally as well as letting them use generalized internal services which encapsulate more complex business operations. An alternative pattern with a small app is to use something like a spring transaction template directly within the UI controller to ‘in-line’ the façade logic into the AJAX UI controller whilst minimizing the scope of the JPA session to the transaction template call-back.

Simon Massey
Simon Massey
12 years ago

@Vincent (said over on his previous blog post comments): If I understand [Simon Massey] correctly, your suggestion is a mix between the two approaches. There is a Service Facade but instead of using DTO’s you have the Service Facade make sure all domain objects are correctly initialized so that you can just return them as-is.
Yes. I just dusted off an re-read the first few chapters of Chris Richardson’s POJOs In Action and found that the approach that I was trying to articulate is strongly influenced by reading his book back in 2006 (written pre-JPA). To summarize his writings:
* His Entities have state and behavior. They are part of the domain model.
* His Services are purely focused on manipulating entities to fulfill use case logic. They are part of the domain model. He says that where possible they delegate logic to the entities.
* The façades return detached entities as the DTOs (“POJO façades that use detached domain objects as DTOs”). They are not part of his domain model. They worry about the plumbing (loading enough data to render on screen and merging detached entities). He is explicit about not copying to DTOs with his case study of a CRUD orientated app.
* He has ‘repositories’ which can be placed today by your DAOs (but I would call them Managers or Repositories to avoid confusion with old-school jdbc backed result set mappers with no lazy-loading).
@Erik rightly points out Chapter 6 of Clean Code which says that we should be very aware of whether we are going for a data structures orientated model or a fully encapsulated object model that shields its internal fields (which we would fire DTOs into or Commands at and hide the internal fields of any entities from the client). The Chris Richardson book and my last three large scale systems fit into the data structures end of the entity spectrum. The services encapsulate the concerns of locking and workflow for the transactional use cases (in the business sense of placing an order as opposed to browsing through data) which have high complexity. Data structure like entities are exposed to the UI don’t need public setters on fields to protected their class invariants.
So my question to is what is the nature of the application for which the DTOs model is recommended in this blog? Is it a online rating engine which needs to follow a command like pattern to hide its internal fields (as recommended by Clean Code chapter 6) or is it a largely crud like app which could fit a data structures model? I feel that the type of logic expose to the client makes a significant impact on the suitability of either the exposed domain model or DTO design. Also whether the client is trusted code or not can have a big impact. If your using a plug-in on the client for UI presentation then you have different concerns about encapsulation of the domain model behind DTOs than with a Swing app or a ZK RIA webapp.

Simon Massey
Simon Massey
12 years ago

@Vincent: The comments to Adam Bien’s posts have a strong negative reaction. In added my own comment. I did put in a caveat that using maps as an impedance mismatch solution when taking to a weak typed client seems okay. In my comment to Adam’s blogg I added an observation to the effect that peer code review cannot always be trusted to catch problems if it is too easy to do the wrong thing in order to cut some corners 😉

trackback

[…] 1. JPA implementation patterns: Service Facades and Data Transfers Objects […]

Sigmund Lundgren
Sigmund Lundgren
12 years ago

ServiceFacade con:
discipline needed, developers tend to implement service/domain logic in the facade. Too common

trackback

[…] Service Facades and Data Transfer Objects […]

Joeri Vandenberghe
Joeri Vandenberghe
12 years ago

Hi,
I layered a bit more…
My Generic Facades use a persistence unit, and implement CRUD functionality.
Then I have Generic Managers who implement the service/domain logic with transactions, there I use the facade interfaces to compose my service/domain specific methods.

juro
juro
11 years ago

Could you send some link for an example app which takes advantage of service facade and DTOs? I can’t find anything and it would help me a lot. Thanks

Srinivas C
Srinivas C
10 years ago

This really is an interesting article. Thanks.

Nils
Nils
10 years ago

I would also greatly benefit from an example implementation of this pattern! Would you be able to publish or send me one?
As a hobby project I am working on a Adobe Flex front-end with a Java back-end using JPA for persistence. The protocol I am using is remote objects (AMF) implemented with BlazeDS.
I started out with a service-facade and entity DAOs, but without any specific DTOs. The same POJOs, the domain objects, were passed in the service-facade as those used as DTOs passed to the Hibernate DAOs.
However, the latest two days I have been thinking whether this is a good approach or not. For example, say I have POJO Book with a unidirection ManyToOne relation with the POJO Category (i.e. each book may only be associated with one category, but the same category may be associated with many books). I see some alternatives:
Alternative 1:
I expose a method/operation addUpdateBook(Book book). In the implementation of this operation I add/update both the book and the referenced category. I mean, if the client submits a book having a category that doesn’t exist from before, this would mean that the client implicitly may edit categories using the addUpdateBook service.
– pro: the client is working directly with the domain model!
– con: the entire category information will be sent when a new book is added even though a reference to the category would be sufficient
Alternative 2:
I expose a method/operation addUpdateBook(Book book,Long categoryId). In the implementation I retrieve the category for the given categoryId and replace the category given in the book POJO and then I persist the book. In other words, I ignore any category in the book object, I just look at the categoryId. This means that the client would need to use another operation in order to modify the category.
– pro: the client can still work on the domain model
– con: it is confusing for the client that the category of the book object will be ignored
– con: the entire category information of the book will be sent, even if the server never will read it
– pro: it may be more clear when a separate operation should be used for category modifications
– con: I need to retrieve the category before persisting the book. I guess this means some overhead.
Alternative 3:
I expose a method/operation addUpdateBook(BookDTO bookDto). The POJO BookDTO looks as the POJO Book, but instead of a field “Category category” it has a field “Long categoryId”. In the implementation I retrieve the Category for the given categoryId before I persist the Book.
– pro: not confusing for the client
– con(?): what should the method getBook(Long bookId) return? should it return only the BookDTO? Then it would be required to invoke also the operation getCategory(Long categoryId) in order to have “the entire book information”. Then the client would need to set together the different parts to a local domain representation of the book. Compared to alternative 1 this would be more complex on the client side?
– con: I need to retrieve the category before persisting the book. I guess this means some overhead.
I guess (!) alternative 3 is the way you would design the operations in a SOA context. However, for me, it is not that important to be loosely-coupled between the client and server. My initial focus is not to provide multiple client-platform support.
Please give me your comments!

Gregory
Gregory
10 years ago

ServiceFacade con: it can easily become a God-object (an anti-pattern) if you don’t follow the clean separation of concerns

Fabio
Fabio
3 years ago

Hi All,
Very interesting article.
DTO/DT can have attributes to help the V of MVC, and if you put in your Domain Object you will create a dirty Domain Object. VO is more about serialization and Service Facade is more about performance, some challenges in Distributed Systems like Single Point of Failure and Security that I can not see in your arguing. Remember that JEE makes possible to put some parts of your application in DMZ others modules in a very secure space.
So a service of Spring can be used remotely.

Explore related posts