How query cache works for scalar results?

五迷三道 提交于 2019-12-11 05:03:16

问题


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:


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();
}


来源:https://stackoverflow.com/questions/8480268/how-query-cache-works-for-scalar-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!