Am计划使用Hibernate 5实现二级缓存。使用@Cacheable注释实体类,并将策略添加为CacheConcurrencyStrategy.READ_WRITE。但它仍在查找数据库中的数据而不是缓存。日志显示2条SQL查询。
请参阅我的主要方法
vbox2.Add(boxSizer, 1, wx.EXPAND | wx.TOP, 3)
vbox2.Add(boxSizer2, 1, wx.EXPAND | wx.TOP, 3)
请参阅HibernateUtil枚举
public static void main(String[] args) {
HolidayDAOImpl holidayImpl = new HolidayDAOImpl();
holidayImpl.setSessionFactory(HibernateUtil.INSTANCE.getSessionFactoryInstance());
holidayImpl.load().forEach(System.out :: println);
System.out.println("Loading second time");
holidayImpl.load().forEach(System.out::println);
}
请参见DAOImpl类
public enum HibernateUtil{
INSTANCE;
public SessionFactory getSessionFactoryInstance(){
Properties properties = new Properties();
properties.setProperty(Environment.URL, "jdbc:mysql://dummy");
properties.setProperty(Environment.DIALECT, "org.hibernate.dialect.MySQLDialect");
properties.setProperty(Environment.DRIVER, "com.mysql.jdbc.Driver");
properties.setProperty(Environment.USER, "demo");
properties.setProperty(Environment.PASS, "demo");
//second level cache prop
properties.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
properties.setProperty(Environment.USE_QUERY_CACHE, "true");
properties.setProperty(Environment.CACHE_REGION_FACTORY, "org.hibernate.cache.ehcache.EhCacheRegionFactory");
//logging
properties.setProperty("hibernate.show_sql","true");
properties.setProperty("hibernate.format_sql","true");
Configuration cfg = new Configuration();
cfg.setProperties(properties);
cfg.addAnnotatedClass(Holidays.class);
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
SessionFactory sessionFactory = cfg.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
pom.xml
public List<Holidays> load() {
try (Session session = sessionFactory.openSession()) {
//List<Holidays> result = session.createQuery("from Holidays", Holidays.class).getResultList();
Criteria criteria = session.createCriteria(Holidays.class);
criteria.add(Restrictions.like("holiday_name", "%QA%"));
return criteria.list();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
在经历一些堆栈溢出答案时,可以理解在最新版本的Hibernate(版本4之后)中,配置有所变化。不确定我在配置中犯了任何错误。
任何人都可以调查它,并弄清楚为什么它仍在寻找数据库而不是缓存吗?
答案 0 :(得分:1)
要使用休眠查询缓存,必须在每个查询中添加setCacheable (true)
。
如果将criteria.setCacheable (true);
添加到DAOImpl类,则第二个查询结果来自缓存。