adam bien's blog

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.