我正在尝试对两个表使用二级缓存,但它仅适用于一个表。我的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/