查询缓存如何用于标量结果? [英] How query cache works for scalar results?

查看:169
本文介绍了查询缓存如何用于标量结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

推荐答案

您可能想看看这篇关于二级缓存的优秀文章

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

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

这篇关于查询缓存如何用于标量结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆