I have a fairly large (new) project in which we have annotated many domain classes with JPA mappings. Now it is time to implement many named queries — some entities may have as many as 15-20 named queries. I am thinking that writing these named queries in annotations will clutter the source files and therefore am considering putting these in XML mapping files.
Is this possible?
Mort importantly, is this reasonable?
Are there better approaches?
How is this done?
Yes it is, but the trend is more to centralize things, not the inverse.
I am not annoyed by a having a block of annotations at the top of my entities class files. Actually, I like to have my queries where I think they belong: next to entities. I also like the compile time checks (on entity names, attributes) and the code completion I get when writing queries in the Java code (not sure my IDE would do that with xml mappings). In other words, I don’t feel the need and don’t want to externalize queries .
I believe that using annotations is the best practice1.
The recommendation is to use XML mapping files only for native SQL statements that are specific to a particular database (of course, I omit the obvious case of legacy code that you can’t annotate). In other words, use annotations but keep the code as free from vendor-specific stuff as possible.
1 The JPA 1.0 specification co-lead Mike Keith covered many of the trade-offs associated with an XML metadata strategy (XML strategy) versus an in-source metadata strategy (annotations strategy) in the OTN column “To Annotate or Not”. Sadly, I couldn’t find a non-dead link to his publication. Maybe you’ll be more lucky and in that case, read it.