Currently, the JPA entities that comprise my application have an @NamedQueries block that contains many @NamedQuery annotations. This works well but some of my entities have over 80 @NamedQuery annotations and are getting difficult to maintain. I now need to add sorting to my queries and do not want to create additional @NamedQuery annotations.
During my research, I discover the JPA 2.1 EntityManagerFactory.addNamedQuery method. This seems to be the answer to my prayers. I could create an initializer that runs at startup to create all my named queries using my established naming conventions and eliminate the large @NamedQueries block at the top of my entities.
I could even use the following EclipseLink specific code to add a new NamedQuery based on an existing NamedQuery.
TypedQuery<Portrait> tq = em.createNamedQuery("Portraits.read", Portrait.class);
String jpql = tq.unwrap(EJBQueryImpl.class).getDatabaseQuery().getJPQLString();
Query q = this.em.createQuery(jpql + " ORDER BY p.id DESC");
em.getEntityManagerFactory().addNamedQuery("Portraits.read.Id-D", q);
TypedQuery<Portrait> tq2 = em.createNamedQuery("Portraits.read.Id-D", Portrait.class);
Are there reasons, I should not use the addNamedQuery method instead of or in addition to the @NamedQuery annotation?