Hibernate实战——查询缓存

╰+攻爆jí腚メ 2021-07-24 23:17 588阅读 0赞

一 配置

  1. <?xml version="1.0" encoding="GBK"?>
  2. <!-- 指定Hibernate配置文件的DTD信息 -->
  3. <!DOCTYPE hibernate-configuration PUBLIC
  4. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  5. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  6. <!-- hibernate-configuration是配置文件的根元素 -->
  7. <hibernate-configuration>
  8. <session-factory>
  9. <!-- 指定连接数据库所用的驱动 -->
  10. <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  11. <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
  12. <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
  13. <!-- 指定连接数据库的用户名 -->
  14. <property name="connection.username">root</property>
  15. <!-- 指定连接数据库的密码 -->
  16. <property name="connection.password">32147</property>
  17. <!-- 指定数据库方言 -->
  18. <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
  19. <!-- 根据需要自动创建数据库 -->
  20. <property name="hbm2ddl.auto">update</property>
  21. <!-- 指定连接池里最大连接数 -->
  22. <property name="hibernate.c3p0.max_size">20</property>
  23. <!-- 指定连接池里最小连接数 -->
  24. <property name="hibernate.c3p0.min_size">1</property>
  25. <!-- 指定连接池里连接的超时时长 -->
  26. <property name="hibernate.c3p0.timeout">5000</property>
  27. <!-- 指定连接池里最大缓存多少个Statement对象 -->
  28. <property name="hibernate.c3p0.max_statements">100</property>
  29. <property name="hibernate.c3p0.idle_test_period">3000</property>
  30. <property name="hibernate.c3p0.acquire_increment">2</property>
  31. <property name="hibernate.c3p0.validate">true</property>
  32. <property name="hibernate.show_sql">true</property>
  33. <property name="hibernate.format_sql">true</property>
  34. <!-- 开启二级缓存 -->
  35. <property name="hibernate.cache.use_second_level_cache">true</property>
  36. <!-- 设置缓存提供者 -->
  37. <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
  38. <!-- 开启二级缓存的统计功能 -->
  39. <property name="hibernate.generate_statistics">true</property>
  40. <!-- 设置使用结构化方式来维护缓存项 -->
  41. <property name="hibernate.cache.use_structured_entries">true</property>
  42. <!-- 启用查询缓存 -->
  43. <property name="hibernate.cache.use_query_cache">true</property>
  44. <!-- 指定根据当前线程来界定上下文相关Session -->
  45. <property name="hibernate.current_session_context_class">thread</property>
  46. <!-- 罗列所有持久化类的类名 -->
  47. <mapping class="org.crazyit.app.domain.News"/>
  48. </session-factory>
  49. </hibernate-configuration>

缓存配置

  1. <?xml version="1.0" encoding="GBK"?>
  2. <ehcache>
  3. <diskStore path="java.io.tmpdir"/>
  4. <defaultCache
  5. maxElementsInMemory="10000"
  6. eternal="false"
  7. overflowToDisk="true"
  8. timeToIdleSeconds="120"
  9. timeToLiveSeconds="120"
  10. diskPersistent="false"/>
  11. </ehcache>

二 PO

  1. package org.crazyit.app.domain;
  2. import javax.persistence.*;
  3. import org.hibernate.annotations.Cache;
  4. import org.hibernate.annotations.CacheConcurrencyStrategy;
  5. @Entity
  6. @Table(name="news_inf")
  7. @Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
  8. public class News
  9. {
  10. // 消息类的标识属性
  11. @Id @Column(name="news_id")
  12. @GeneratedValue(strategy=GenerationType.IDENTITY)
  13. private Integer id;
  14. private String title;
  15. private String content;
  16. // 无参数的构造器
  17. public News()
  18. {
  19. }
  20. // 初始化全部成员变量的构造器
  21. public News(Integer id , String title , String content)
  22. {
  23. this.id = id;
  24. this.title = title;
  25. this.content = content;
  26. }
  27. // id的setter和getter方法
  28. public void setId(Integer id)
  29. {
  30. this.id = id;
  31. }
  32. public Integer getId()
  33. {
  34. return this.id;
  35. }
  36. // title的setter和getter方法
  37. public void setTitle(String title)
  38. {
  39. this.title = title;
  40. }
  41. public String getTitle()
  42. {
  43. return this.title;
  44. }
  45. // content的setter和getter方法
  46. public void setContent(String content)
  47. {
  48. this.content = content;
  49. }
  50. public String getContent()
  51. {
  52. return this.content;
  53. }
  54. }

三 测试

  1. package lee;
  2. import org.hibernate.*;
  3. import org.hibernate.cfg.*;
  4. import org.hibernate.service.*;
  5. import org.hibernate.boot.registry.*;
  6. import java.util.*;
  7. import org.crazyit.app.domain.*;
  8. public class NewsManager
  9. {
  10. static Configuration conf = new Configuration()
  11. .configure();
  12. // 以Configuration实例创建SessionFactory实例
  13. static ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
  14. .applySettings(conf.getProperties()).build();
  15. static SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
  16. public static void main(String[] args) throws Exception
  17. {
  18. NewsManager mgr = new NewsManager();
  19. mgr.cacheQuery();
  20. mgr.stat();
  21. }
  22. private void noCacheQuery()
  23. {
  24. Session session = sf.getCurrentSession();
  25. session.beginTransaction();
  26. List titles = session.createQuery("select news.title from News news")
  27. // 其实无需设置,默认就是关闭缓存的。
  28. .setCacheable(false)
  29. .list();
  30. for(Object title : titles)
  31. {
  32. System.out.println(title);
  33. }
  34. System.out.println("-------------------------");
  35. // 第二次查询,因为没有使用查询缓存,因此会重新发出SQL语句进行查询
  36. titles = session.createQuery("select news.title from News news")
  37. // 其实无需设置,默认就是关闭缓存的。
  38. .setCacheable(false)
  39. .list();
  40. for(Object title : titles)
  41. {
  42. System.out.println(title);
  43. }
  44. session.getTransaction().commit();
  45. }
  46. private void cacheQuery()
  47. {
  48. Session session = sf.getCurrentSession();
  49. session.beginTransaction();
  50. List titles = session.createQuery("select news.title from News news")
  51. // 开启查询缓存
  52. .setCacheable(true)
  53. .list();
  54. for(Object title : titles)
  55. {
  56. System.out.println(title);
  57. }
  58. session.getTransaction().commit();
  59. System.out.println("-------------------------");
  60. Session sess2 = sf.getCurrentSession();
  61. sess2.beginTransaction();
  62. // 第二次查询,使用查询缓存,因此不会重新发出SQL语句进行查询
  63. titles = sess2.createQuery("select news.title from News news")
  64. // 开启查询缓存
  65. .setCacheable(true)
  66. .list();
  67. for(Object title : titles)
  68. {
  69. System.out.println(title);
  70. }
  71. sess2.getTransaction().commit();
  72. }
  73. // 开启查询缓存,但使用iterate()方法查询,因此也不能缓存
  74. public static void cacheQueryIterator()
  75. {
  76. Session session = sf.getCurrentSession();
  77. session.beginTransaction();
  78. Iterator it = session.createQuery("select news.title from News news")
  79. // 开启查询缓存
  80. .setCacheable(true)
  81. .iterate();
  82. while(it.hasNext())
  83. {
  84. System.out.println(it.next());
  85. }
  86. session.getTransaction().commit();
  87. System.out.println("-------------------------");
  88. Session sess2 = sf.getCurrentSession();
  89. sess2.beginTransaction();
  90. // 第二次查询,虽然使用了查询缓存,但由于使用iterate()获取查询结果,
  91. // 因此无法利用查询缓存。
  92. it = sess2.createQuery("select news.title from News news")
  93. // 开启查询缓存
  94. .setCacheable(true)
  95. .iterate();
  96. while(it.hasNext())
  97. {
  98. System.out.println(it.next());
  99. }
  100. sess2.getTransaction().commit();
  101. }
  102. private void stat()
  103. {
  104. //----------统计查询缓存----------
  105. long hitCount = sf.getStatistics()
  106. //查询缓存的名字与HQL语句或SQL语句相同
  107. .getQueryStatistics("select news.title from News news")
  108. .getCacheHitCount();
  109. System.out.println("查询缓存命中的次数:" + hitCount);
  110. }
  111. }

四 数据

  1. drop database hibernate;
  2. create database hibernate;
  3. use hibernate;
  4. create table news_inf
  5. (
  6. news_id int primary key auto_increment,
  7. title varchar(255),
  8. content varchar(255)
  9. );
  10. insert into news_inf
  11. values(null , '疯狂Java联盟' , '疯狂Java联盟成立了,网址是www.crazyit.org');
  12. insert into news_inf
  13. values(null , '天快亮了' , '等到那一天,四周一下光亮了,空气中酝酿着自由、民主的芬芳!');

五 测试

  1. Hibernate:
  2. select
  3. news0_.title as col_0_0_
  4. from
  5. news_inf news0_
  6. 疯狂Java联盟
  7. 天快亮了
  8. -------------------------
  9. 疯狂Java联盟
  10. 天快亮了
  11. 查询缓存命中的次数:1

发表评论

表情:
评论列表 (有 0 条评论,588人围观)

还没有评论,来说两句吧...

相关阅读

    相关 hibernate查询缓存

    在hibernate的使用中,大家多数时间都在讨论一级缓存和二级缓存,而往往忽略了查询缓存。其实hibernate的查询缓存在使用过程中也起着同样重要的作用。hibernate

    相关 hibernate查询缓存

    在hibernate的使用中,大家多数时间都在讨论一级缓存和二级缓存,而往往忽略了查询缓存。其实hibernate的查询缓存在使用过程中也起着同样重要的作用。hibernate

    相关 Hibernate查询缓存

     在hibernate的使用中,大家多数时间都在讨论一级缓存和二级缓存,而往往忽略了查询缓存。其实hibernate的查询缓存在使用过程中也起着同样重要的作用。hibernat