java - Ehcache 只对 Hibernate 中的一张表起作用

标签 java mysql hibernate caching ehcache

我正在尝试对两个表使用二级缓存,但它仅适用于一个表。我的ehcache.xml配置如下

<?xml version="1.0"?>  
<ehcache>  
 <defaultCache   
   maxElementsInMemory="100"   
   eternal="false"   
   timeToIdleSeconds="120"   
   timeToLiveSeconds="200" />  

   <cache name="com.cni.Employee"   
   maxElementsInMemory="100"   
   eternal="false"   
   timeToIdleSeconds="10"   
   timeToLiveSeconds="200" />  

   <cache name="com.cni.Person"   
   maxElementsInMemory="100"   
   eternal="false"   
   timeToIdleSeconds="10"   
  timeToLiveSeconds="200" />  

</ehcache>  

仅缓存“Employee”类。我第一次在类里面只能看到一个 SQL 查询。但对于“Person”类,每次我访问 Web 服务时,它总是显示 SQL 查询。我还需要配置其他东西吗?

我的 Person 类是

 @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@Entity
@Table(name = "person")
public class Person {
@Override
public String toString() {
    return "Person [id=" + id + ", userId=" + userId
            + ", courseId=" + courseId + ", courseValue=" + courseValue
            + "]";
}
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String userId;
private String courseId;
private String courseValue;

我的选择查询代码

public JSONObject getCourseDetails(String id) {

    System.setProperty("net.sf.ehcache.skipUpdateCheck", "true");
    JSONObject obj = new JSONObject();       
    try (Session session = factory.openSession()) {
        String hql = "FROM Person E WHERE E.userId = "+id;
        Query query = session.createQuery(hql);
        List<?> results = query.list();
        Gson gson = new Gson();
        String jsonCourseList = gson.toJson(results);
        System.out.println("Course JSON Data: " + jsonCourseList);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return obj;
}   

最佳答案

JPQL/HQL 始终在数据库中执行。然后根据查询结果集中的id从二级缓存中获取实体。

如果是session.load方法,则直接通过提供的id从二级缓存中获取实体。不需要在数据库中执行查询,因为 id 已经知道。

关于java - Ehcache 只对 Hibernate 中的一张表起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36148201/

相关文章:

java - 使用反射解包数组

java - 使用插入排序、双向链表对字符串数组索引进行排序

java - try/catch block 捕获异常有什么意义?

java - JVM 故障转储中的标准并行 GC 被称为什么?

hibernate - 如何使用Grails获取映射到另一个对象内的对象的所有属性

mysql - 在这种情况下如何在MySQL中使用连接

mysql - Asterisk 实时用户注册

mysql更新触发旧、新行的列日志

java - 如何使用 Hibernate 映射 java.time.Year 和其他 java.time 类型

java - websphere8.5.0.0中如何获取UserTransaction?