How query cache works for scalar results?

2019-07-27 11:06发布

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?

1条回答
ら.Afraid
2楼-- · 2019-07-27 11:42

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 return emp.getEmployeeCode() in your DAO method to take advantage of the 2nd level and query cache:

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
class Employee {
  @Column
  Integer employeeCode;
}


public Integer getEmployeeCode(String userName) {
  Session session = sessionfactory.getCurrentSession();
  Query q = session.createQuery("from Employee emp where emp.userName = :username");
  q.setString("username", userName);
  Employee emp = q.setCacheRegion("Employee").setCacheable(true).uniqueResult();
  return emp.getEmployeeCode();
}
查看更多
登录 后发表回答