Few days ago I started to read Robert C. Martin "Clean Code" book and it encouraged me to look more detailed at my code. After I opened eclipse I saw this:


and I decided to move string CarriageRouteEntity.listCarriageDirections to constant string. After quick fix I created something like this:

        @NamedQuery(name = CarriageRouteEntity.LIST_CARRIAGE_DIRECTIONS, query = "just query ...") })
public class CarriageRouteEntity {
    public static final String LIST_CARRIAGE_DIRECTIONS = "CarriageRouteEntity.listDirections";
    // ...

so now I call it like this:


And here I started to wondering where should I put named queries constants. Is entity class good place for this? Maybe I should create new class with these constants like

public class CarriageRouteEntityNamedQuery {
        public static final String LIST_CARRIAGE_DIRECTIONS = "CarriageRouteEntity.listDirections";

but if another programmer will try to create named query will he knew where to look at it? What are your opinions? How to organize these constants? Maybe instead of creating CarriageRouteEntityNamedQuery class I should create enum and add method to entity CarriageRouteEntity called getNamedQuery() which will tell another programmer in which enum he/she should look for constants?


I've done both of the approaches you've mentioned and both are equally as useful. Depending on how your architecture is set up, there are some conditions you might want to consider:

1.) If you have less than 7 or 8 named queries, I would consider putting them as constants in the same class as your data access methods if and only if the named queries are used in that class.

2.) If you have more than 8 named queries or you have multiple named queries spread across multiple entity classes that you'd like to store in a single location, I would definitely put those in a separate class as constants.

Be sure to place your named query classes as close to your entity classes as possible.


Is there a reason you are avoiding using an Enum for this?

That is:

    public enum NamedQueryEnum {
       // additional query names get added here

       private String queryName;

       private NamedQueryEnum( String queryName) {
          this.queryName= queryName;

      public Query getQuery(EntityManagager entitymanager) {
          return entityManager.createNamedQuery(entityManager.createNamedQuery(queryName));

Then your call would be:

  • +1 Great answer! Of course there is no reason. I'm just wondering what is the best way to do it. BTW. I think that it will be better to avoid passing entityManager as a parameter to getQuery method but it can be the next step to improve it. – pepuch Feb 9 '14 at 18:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.