Hibernate之查询缓存

<property name="hibernate.cache.use_query_cache">true</property>

try {/** * 此时会发出一条sql取出所有的学生信息 */session = HibernateUtil.openSession();Listls = session.createQuery("from Student").setCacheable(true)//开启查询缓存,查询缓存也是SessionFactory级别的缓存.setFirstResult(0).setMaxResults(50).list();Iteratorstus = ls.iterator();

for(;stus.hasNext();) {

Student stu = stus.next();

System.out.println(stu.getName());

}

* 会发出SQL取完整的学生对象,占用内存相对较多

ls = session.createQuery("from Student")

.setCacheable(true)

.setFirstResult(0).setMaxResults(50).list();

stus = ls.iterator();

for(;stus.hasNext();) {

Student stu = stus.next();

System.out.println(stu.getName());}

} catch (Exception e) {

e.printStackTrace();

} finally {

HibernateUtil.close(session);}

只要HQL语句不一样,就不会开启查询缓存,查询缓存是是HQL语句,只有两个HQL语句完全一样(并且参数都要一致)才会使用查询缓存。

try {/** * 查询缓存缓存的不是对象而是id */session = HibernateUtil.openSession();Listls = session.createQuery("from Student where name like ?").setCacheable(true)//开启查询缓存,查询缓存也是SessionFactory级别的缓存.setParameter(0, "%王%").setFirstResult(0).setMaxResults(50).list();Iteratorstus = ls.iterator();for(;stus.hasNext();) {Student stu = stus.next();System.out.println(stu.getName());}} catch (Exception e) {e.printStackTrace();} finally {HibernateUtil.close(session);}session = null;try {/** * 查询缓存缓存的是id,此时由于在缓存中已经存在了这样的一组学生数据,但是仅仅只是缓存了 * id,所以此处会发出大量的sql语句根据id取对象,这也是发现N+1问题的第二个原因 * 所以如果使用查询缓存必须开启二级缓存 */session = HibernateUtil.openSession();Listls = session.createQuery("from Student where name like ?").setCacheable(true)//开启查询缓存,查询缓存也是SessionFactory级别的缓存.setParameter(0, "%王%").setFirstResult(0).setMaxResults(50).list();Iteratorstus = ls.iterator();

for(;stus.hasNext();) {

Student stu = stus.next();

System.out.println(stu.getName());}

} catch (Exception e) {

e.printStackTrace();

} finally {

HibernateUtil.close(session);}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容