JPA: XML overrides Annotations
Java EE APIs operate in the "Convention over Configuration" or "Configuration by Exception" mode:
- APIs ship with suitable defaults
- Defaults can be overridden / supplemented via annotations
- Annotations can be overridden / supplemented via XML descriptors
- 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:
- Product development: generic mappings can be partially adjusted during installation without recompiling the code
- Data migrations: entities are read from one persistence unit fully relying on annotations and writing to a persistence unit augmented by orm.xml
- Integration of external libraries / third party code: JavaBeans without existing source code can be augmented with orm.xml and turned into entities
- Separated read / write databases: a dedicated
EntityManageris used for reading, another for writing. The database instances used behind the
EntityManagermay 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.
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 #