I am new to Hibernate and I have the following piece of code in my DAO implementation class:
public Integer getEmployeeCode(String userName) {
Session session = sessionfactory.getCurrentSession();
Query q = session.createQuery("select emp.employeeCode from Employee emp where emp.userName = :username");
q.setString("username",userName);
Integer p = (Integer) q.setCacheRegion("UserNameToCode").setCacheable(true).uniqueResult();
I am using Hibernate with EhCache. I am wondering if I am using query cache correctly here? I understand that for domain objects, the query caches stores the mapping from query string and binding parameters to primary keys. However, how is the scalar values being cached in memory?
You might want to take a look at this excellent article about the 2nd level cache.
I am not quite sure, but I think you should not query for the scalar value but query the
Employee
by userName and returnemp.getEmployeeCode()
in your DAO method to take advantage of the 2nd level and query cache: