views:

615

answers:

1

Are there any advantages of using named queries vs what we have? Looking at performance, usability, maintainability etc etc....

In our application we have defined our queries as such:

private static final String SELECT_CODE_FOR_STORE = "select DISTINCT code from Code code "
        + "join code.codeDescriptions codeDesc "
        + "join codeDesc.stores store where store.id =:"
        + DataAccessConstants.PARAM_STORE_ID;

(These are all placed into the DAO object and there are many of them.)

And we call the above by using:

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeId", codeDescriptionSearchCriteria.getStoreId());
        List<Code> list = getJpaTemplate().findByNamedParams(
                SELECT_CODE_FOR_STORE, paramMap);
        return list;

Which is nothing more then:

    public List findByNamedParams(final String arg0, 
                                  final Map<String, 
                                  ? extends Object> arg1) throws DataAccessException 
    {
      return org.springframework.orm.jpa.JpaTemplate.findByNamedParams(arg0, arg1);
    }

As compared to using

@NamedQuery(name="SELECT_CODE_FOR_STORE", query="select ......")

A the top of our DAO objects.

I saw this posting which seems to be a good way to organize all these queries. Or maybe it is time to re-evaluate our database and object structures if we have so many of these type of queries.

+1  A: 

I use the second approach in the question you linked to (named queries with string constants ). The main advantage of using named queries is that Hibernate parses the queries at startup so any errors will detected quickly.

As for your overall approach I would definitely question your domain model if you need named queries a lot. For some applications this is necessary but maybe look at replacing joins with lazy loads in the entities. Also look at using hobernate query by example and criteria as these can also reduce use of named queries in an object orientated way.

Pablojim