I got this tip a while back and have constructed my JPA Dao lookup methods like this:
Basically, instead of returning the entire object, i only return the ID in the query, then use findById to look up the entire object which i know is cached in the second level cache:
JPA Query:
SELECT u.id FROM User u WHERE email=:param
DAO method:
public User findByEmail(String parameter){
TypedQuery<Long> q = getEntityManager().createNamedQuery("User.findByEmail", Long.class);
q.setParameter("param", parameter);
q.setHint("org.hibernate.cacheable", true);
q.setHint("org.hibernate.cacheRegion", "query.user");
List<Long> res = q.getResultList();
if (res != null && res.size() > 0) {
return findById(res.get(0));
}
return null;
}
But now i've looked at some blog posts, for example here: enter link description here Most specifically:
The query cache looks conceptually like an hash map where the key is composed by the query text and the parameter values, and the value is a list of entity Id's that match the query:
But if this is the case, how much does it matter that i only read and return the ID's in my actual query? The objects aren't stored in the query cache anyway, only the id's. It seems like hibernate is already doing what i'm trying to optimize?
OK, when i read it from the database i suppose that a little bit less data needs to be read up in memory, but other than that i'm not sure if it matters.
Is there any other benefit to what i'm doing, i.e. just reading the id's, or is there even a drawback?