0

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?

Mathias
  • 3,879
  • 5
  • 36
  • 48
  • You may want to look at this answer here http://stackoverflow.com/a/3180412/258741. bottom line, the database performance is same for one column or multiple columns. The same applies to the data to object mapping done by the Hibernate, it would not make much difference, may be it will add .001 additional second when mapping other columns to the pojo. – Zeus Mar 10 '16 at 22:18
  • Thanks mate. However, that question is more about database performance and how the reading of columns work. My question is more about memory consumption in the VM, and whether just reading the id's vs. all the columns matter. But i suppose it doesn't, much. – Mathias Mar 11 '16 at 08:45

0 Answers0