< Java
Blog >
The cons of JPA annotations
Harry Klerks

Every now and then, I find myself being part of a discussion about some aspect of Software Development. Nice pastime, albeit sometimes a bit tiring since many of these discussions tend to develop into pseudo-religious debates that I find hard to stomach. That is usually the moment to start looking for the exit.

One of the subjects that usually gets me in a spot of bother is the use (or lack thereof) of JPA ORM annotations in the domain classes in the Java-based software systems that I develop. I never use these annotations and I think I have good reasons for it.

The basic mode of operation is usually that there is a module in an application that contains a collection of entity classes that you might call a 'domain' (other terms are also used, but I think this is the most common). These entity classes contain JPA annotations to describe the ORM for them and there is a persistence.xml file somewhere in the same module to describe higher level stuff such as datasource referencing, configuration, schema generation, etc.

I see this so often, that I fear that it is considered a good, or even best, practice? I beg to differ.

The most important reason not to use these annotations is that I believe it is plain wrong to do so. Simply put, the domain may have knowledge about certain persistence aspects, but not about the implementation details. And no matter how you shake or dance, these ORM annotations are metadata describing implementation details. For one thing they explicitly state that the persistence model is relational.

Another reason is of a more practical nature. When describing the ORM in an XML file, I have the entire mapping in one place instead of scattered over any number of Java source files. And even though I share a dislike of bloated XML configuration files with many of you, I don't find that a very strong argument. Get yourself a half decent IDE and most of the pain is taken away from you. Hell, even Eclipse has a proper way of dealing with this nowadays... (but admittedly makes a dog's dinner of many other features (sad)).

Now, all I have to do is make sure that the entity classes are on the classpath of the ORM mapping file and the persistence.xml file and Bob's your uncle

Another advantage of this approach is that you never expose ORM annotated entity classes to other ' persistence-aware' contexts by accident.