【问题标题】:How query cache works for scalar results?查询缓存如何处理标量结果?
【发布时间】:2011-12-12 20:18:50
【问题描述】:

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

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

【问题讨论】:

    标签: java hibernate caching ehcache query-cache


    【解决方案1】:

    您可能想看看this excellent article about the 2nd level cache

    我不太确定,但我认为您不应该查询标量值,而是通过用户名查询 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多