In general, is it a better practice to write a new NamedQuery which selects a field,
@NamedQuery(name="getEntityField",
query="select e.field from Entity e where <condition>")
or should one select e from Entity... and then build a new list?
List<Entity> entities = query.getResultList();
List<Object> fields = new ArrayList<Object>();
for (Entity e : entities) {
fields.add( e.getField() );
}
If one of these patterns is better, why?
When you do it with a
NamedQuery, the database only has to send a list with the content of that field back to the application, instead of complete entities (all the columns of a table).On the other hand, if the entities are already in the cache of your ORM framework, then to get the entities it doesn’t even have to go to the database at all.
It might also be that your ORM framework is smart enough to understand the query, so that it can do the query from its cache instead of going to the database.
What works best depends on the situation of your application and the ORM framework that you are using. Try out both methods, let your ORM framework log what it does, and look through the log to see what it does and determine which is better for your particular application.