简体   繁体   中英

hibernate & JAXB/JSON (Message Model & Data Model)

This is a design philosophy question on how closely to bind your message exchange to your data model.

Given an entity pojo, I can annotate it with Hibernate, JAXB and JSON annotations so that the same class can be written to the database as well as serialize/deserialize for message exchange. The convenience factor in this is really high because it means I don't have to write translation classes to convert the messages to the classes that are used for the database (which is big on the tedium and maintenance).

However, this always bothered me because it throughly ties your interface and messages with the structure and design of your data model. For certain types of applications, the messages might be exactly what you want to store in the database, and other times it's a subset of the database fields.

Is there a better way to decouple these without subjecting yourself to tedious translation/conversion classes? Is there a pattern I can use to at least better couple the message and data?

I totally agree with your concern... it is one gray area because it really depends on your domain problems you are trying to solve.

If your project simple and straightfoward, then I might just annotate the entities and be done. This way, the consumer (ex: Javascript code) basically picks out the data needed to display on the page. In this case, you are in-charge in reading the JSON/XML and do whatever you like.

However, if you are doing writing web services to be exposed to other folks, the data usually comes from different entities (table joins). In this case, it makes no sense to return such complex JSON/XML that is so tightly coupled to the actual entity structure. If you decide to refactor your entities one day, then all your consumers will be negatively impacted. Thus, it is better to create separate beans that reflects the summarized data intended for the consumers rather than relying on your existing entity beans. This way, the generated JSON/XML will be able to withstand future changes and minimizes negative ripple effect.

You can leverage the @XmlPath extension in EclipseLink JAXB (MOXy) to break the relationship between then entity model and the message format (I'm the MOXy tech lead):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM