14

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?

Jens Piegsa
  • 7,399
  • 5
  • 58
  • 106
Clinton Bosch
  • 2,497
  • 4
  • 32
  • 46

2 Answers2

12

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.

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
  • 2
    I believe `Entity.camelCaseWhatItDoesName` pretty much qualifies as a best practice. In past projects, several customers have adopted this style. – Kawu Mar 19 '14 at 12:41
5

Although there doesn't seem to be a globally accepted best practice, the book "Pro JPA 2" by Mike Keith and Merrick Shincariol recommends exactly what Mikko said, e.g. if you have a query for finding all Employees then call it "Employee.findAll".

Ito where to declare these, again there is no real best practice from what I can see. They seem to tend to favour declaring them on the Entity itself rather than all in one big class (such as a base MappedSuperclass from which all your entities extend) since that would very quickly become monolithic and could be a bit hard to maintain. Another option is to declare them in a separate XML file, not that I would recommend that. Personally I like the approach where they are declared on the Entity that they are related to. I also agree with Miko's suggestion to use constants for the name, you could just define all of these constants in a separate class.

brent777
  • 3,369
  • 1
  • 26
  • 35
  • as an aside, one best practice that is highly recommended for named queries is to use named parameters as opposed to positional parameters. This makes the queries a lot easier to work with. – brent777 Jun 08 '12 at 09:25