Adam Bien's Weblog

JPA: XML overrides Annotations

Java EE APIs operate in the "Convention over Configuration" or "Configuration by Exception" mode:

  1. APIs ship with suitable defaults
  2. Defaults can be overridden / supplemented via annotations
  3. Annotations can be overridden / supplemented via XML descriptors
  4. XML descriptors can be overridden via dedicated extension points, hooks (not available for all APIs)

JPA entities in particular can be deployed with minimalistic set (@Entity / @ID) of annotations first and overridden on demand:

"XML metadata may be used as an alternative to these annotations, or to override or augment annotations (...)"
[Chapter 11, Page 421, JSR-388: Java Persistence 2.1]

In JPA, supplementing, or even replacing annotations with orm.xml eases realization of following use cases:

  1. Product development: generic mappings can be partially adjusted during installation without recompiling the code
  2. Data migrations: entities are read from one persistence unit fully relying on annotations and writing to a persistence unit augmented by orm.xml
  3. Integration of external libraries / third party code: JavaBeans without existing source code can be augmented with orm.xml and turned into entities
  4. Separated read / write databases: a dedicated EntityManager is used for reading, another for writing. The database instances used behind the EntityManager may require mapping adjustments

However: premature configuration is the root of (all) evil. Most of the Java EE projects come without any configuration or XML and they fully rely on conventions "salted" with only a few annotations.


NEW workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

The annotations have their own benefits and can be used to configure the defaults. In a packaged application the XMLs can be used to override these defaults when access to the code is restricted.

One such scenario is product/platform customization while configuring for client specific deployments. Typically, in such configurations the base product/platform code is not modified directly but extended through well defined extension points or customization hooks.

Unfortunately, the existing JPA specs do not support the same level of configuration capabilities via XML which are otherwise available through annotations.

Hibernate HBM files suited this requirement perfectly whereas the current ORM XML structure is implemented more like an afterthought.

Posted by Mrinal Kanti on July 22, 2015 at 08:42 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License