NamedQuery: Best practices
java, jpa, naming-conventions
Solution
No, there is no widely accepted best practice that covers any complex cases. Also in general there is not too much style guides available for JPA. What seems to be commonly accepted, and in general used in books as well, is to start query with name of the entity.
I would go for EntityName (to guarantee unique names in persistence unit) combined with operation and arguments.
- Person.findByAge
- Person.findByAgeAndFirstName
- Person.removeByFirstName
- Person.updateSalaryIfYearBornBefore
Just as a note, specification uses `with` instead of `by` in examples, and does not prefix query with name of the entity. But that is of course specification, not style guide.
I find it good to declare constants for these query names and then use these constants in both @NamedQuery.name and em.createNamedQuery.
Because @NamedQuery, @NamedNativeQuery, and @NamedQueries can only be applied to mapped superclass or entity, you cannot locate them to utility class.
Problem
When creating named queries in JPA, is there an accepted best practice for the names of these queries (eg. `EntityName.allActive` or `findAllActiveFoos` etc.) and also is it good to declare these named queries in the entity classes that they query or all together in a utility class?