Hibernate 系列教程17-查询缓存
在二级缓存配置成功的基础上进行查询缓存配置
Product
public class Product {
private Long id;
private String name;
Product.hbm.xml
<class name="Product">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
</class>
MainTest
public class MainTest {
@Before
public void save() throws Exception {
Product product = new Product();
product.setName("xxxx");
Session session = HibernateUtils.INSTANCE.getSession();
session.beginTransaction();
session.save(product);
session.getTransaction().commit();
session.close();
}
// 模拟同一个SessionFactory,不同session获取hql查询
// 查询缓存需要先配置类的二级缓存
// 只发出一条sql:查询缓存命中
@Test
public void get() throws Exception {
Session session1 = HibernateUtils.INSTANCE.getSession();
String hql = "select p from Product p";
Query query = session1.createQuery(hql);
// 放入查询缓存
query.setCacheable(true);
System.out.println(query.list().size());
session1.close();
Session session2 = HibernateUtils.INSTANCE.getSession();
String hql2 = "from Product";
Query query2 = session2.createQuery(hql2);
// 从查询缓存取
query2.setCacheable(true);
System.out.println(query2.list().size());
session2.close();
}
}
源码地址
https://github.com/je-ge/hibernate
如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!