【问题标题】:Caching with Echache + hibernate使用 Echache + hibernate 进行缓存
【发布时间】:2011-09-03 06:00:27
【问题描述】:

嗨,在我的应用程序中,我有几个小表,我在服务器启动时将它们全部缓存在 Map 中。我想通过 Ecache + hibernate 组合实现相同的功能

我的班级看起来像

  @Entity
  @Table(name = "Order")
  @NamedQueries
  ({
     @NamedQuery(name="Order.findBySource", 
        query="from Order a where a.source = :source"),

     @NamedQuery(name="Order.findByAll", 
        query="from Order"),

     @NamedQuery(name="Order.findByPrioritySource", 
        query="from Order a where a.priority = :priority and a.source =   :source"),

     @NamedQuery(name="Order.findByPriority", 
        query="from Order a where a.priority = :priority"),

     @NamedQuery(name="Order.findByWhenModified", 
        query="from Order a where a.whenModified = :whenModified")
     })
      @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)

    public class Order implements java.io.Serializable {

      private String source;
      private long priority;
      private Date whenModified;
    }

这个订单表几乎没有 10 个条目,我想一直将此表保存在内存中。 任何见解我该如何实现这一目标?

我触发上述命名查询以获取订单。当我触发这个查询时,我不想一次又一次地去数据库,所以在 ecache.xml 中我需要输入这个类吗?或者我需要在 ecache.xml 中缓存这些命名查询?

是否可以通过 Ehcache 复制 Map 实现。这样我就可以通过从缓存中指定 ID 来获取对象,而无需一次又一次地访问数据库?

【问题讨论】:

    标签: hibernate caching orm jpa-2.0 ehcache


    【解决方案1】:

    您需要的是 Hibernate 查询缓存。首先,您需要通过将 hibernate.cache.use_query_cache 属性设置为 true 在 Hibernate 级别启用它。然后,当您在代码中执行查询时,您需要在查询对象上设置一个标志以指示它需要缓存:

    Query q = session.getNamedQuery("Order.findByPriority");
    q.setCacheable(true);
    List result = q.list();
    

    【讨论】:

    猜你喜欢
    • 2017-05-11
    • 2013-06-23
    • 2011-07-21
    • 2010-12-16
    • 2017-02-25
    • 2015-04-04
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多