views:

631

answers:

3

I have a Java enterprise application that provides a web service, has a domain layer, and a hibernate persistence layer. In this particular case, there is not a huge difference (at the moment) between the objects I send over the wire, the domain objects, and the persistence objects.

Currently the application uses DTO's on the persistence side and annotates the Domain classes with JAXB annotations. However, the more I read and think about it, the more this seems backwards! (Not to mention there is a lot of code to support the mindless back and forth between the DTO's and the Domain objects.) It seems like most architects suggest puting JPA annotations on the domain model and create DTO's for sending objects over the wire.

In my case, could I put both the JAXB and JPA (Hibernate) annotations on my domain classes?

The thought of keeping my web service facade, my domain, and my persistence all tightly bundled together seems easy to maintain, but does concern me as these may need to change in time. But would it be smarter to create a set of DTO classes for the web services side and skip the DTO's for the persistence side?

+3  A: 

There's no functional reason for not annotating the same class with both JPA and JAXB annotations, I've done it myself on occasion. It does become a bit hard to read, though, and sometimes you want different class design trade-offs with JAXB and JPA. In my experience, these trade-offs usually mean you end up with two class models.

skaffman
Makes sense that sooner or later you'll need to separate them into layers. But in a brand new project, it saves a lot of time to combine them. Good to know there's no bad side effects of doing this.
HDave
+1  A: 

There is no problem in using both annotations on the same class. I even tend to encourage this, because thus you don't have to copy-paste when changes occur. In some cases, some properties differ in behaviour - for example an auto-generated ID might not be required to be marshalled. @XmlTransient and @Transient are then combined. It does become a bit hard to read, but not too hard, because it is obvious what all the annotations mean.

Bozho
+1  A: 

I agree that using the same model classes is the right approach. If you are concerned about annotation clutter, you could use a JAXB implementation (such as EclipseLink JAXB) that provides a mechanism for externalizing the metadata:

Also since you are using a JPA model EclipseLink JAXB (MOXy) has extensions for making this easier:

Here is an example of using one model with JAXB & JPA to create a RESTful service:

Blaise Doughan