查询缓存如何用于标量结果?

时间:2011-12-12 20:18:51

标签: java hibernate caching ehcache query-cache

我是Hibernate的新手,我在DAO实现类中有以下代码:

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

我正在使用Hibernate和EhCache。我想知道我是否在这里正确使用查询缓存?我理解,对于域对象,查询缓存存储从查询字符串和绑定参数到主键的映射。但是,标量值如何缓存在内存中?

1 个答案:

答案 0 :(得分:0)

您可能需要查看this excellent article about the 2nd level cache

我不太确定,但我认为你不应该查询标量值,而是通过userName查询Employee并在DAO方法中返回emp.getEmployeeCode()以利用第二级和查询缓存:

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