hibernate4 二级缓存demo实例

public static void main(String[] args) {
 
  DeptEntity dept = getDept(“402882e762ae888d0162ae888e420000”);

转载:

  //dept.getEmp()得到子表的记录集合
  System.out.println(dept.getEmp());

hibernate使用版本是:hibernate-release-4.3.4.Final

}

需要的jar包:hibernate-release-4.3.4Final\lib\required下所有jar包

private static DeptEntity getDept(String did){
  Session session = sessionFactory.openSession();
  DeptEntity dept = (DeptEntity)session.get(DeptEntity.class, did);
  session.close();
  return dept;
}

ehcache 
jar包:hibernate-release-4.3.4.Final\lib\optional\ehcache下所有包

 

junit:junit-4.10.jar和mysql-connector-java-5.1.15-bin.jar

运行结果:

注:hibernate
4.2.5版本ehcache缓存不依赖commons-logging-1.1.1.jar,需要的是slf4j-api-1.6.1.jar

Exception in thread “main” org.hibernate.LazyInitializationException:
failed to lazily initialize a collection of role:
com.javakc.hibernate.onetomany.entity.DeptEntity.emp, could not
initialize proxy – no Session
at
org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
at
org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
at
org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
at
org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124)
at
org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:326)
at java.lang.String.valueOf(String.java:2827)
at java.io.PrintStream.println(PrintStream.java:771)
at
com.javakc.hibernate.onetomany.action.TestAction.main(TestAction.java:74)

项目结构如下
 
图片 1
 

 

hibernate.cfg.xml

集合延迟加载初始化失败,不能初始化一个代理。就是集合在非一对一对象关系中,为了节省资源是默认延迟加载,而get方法又是非延迟加载,所以在执行完一次数据库查询后就执行session.close();关闭了session,而集合是延迟加载,在使用集合时再加载,此时session已经关闭,所以得不到代理。解决方法:可以在主表的hbm配置文件中,在<set>标签里设置lazy=”false”,集合就不延迟加载了,因此在执行get方法时,集合也获取到了,就不会出现延迟加载问题了。

  1. <?xml version=’1.0′ encoding=’utf-8′?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.         “-//Hibernate/Hibernate Configuration DTD 3.0//EN”  
  4.         “;  
  5. <hibernate-configuration>  
  6.     <session-factory>  
  7.         <!– Database connection settings –>  
  8.         <property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>  
  9.         <property name=”connection.url”>jdbc:mysql://127.0.0.1:3306/hibernate4</property>  
  10.         <property name=”connection.username”>root</property>  
  11.         <property name=”connection.password”>root</property>  
  12.         <!– JDBC connection pool (use the built-in) –>  
  13.         <property name=”connection.pool_size”>1</property>  
  14.         <!– SQL dialect –>  
  15.         <property name=”dialect”>org.hibernate.dialect.MySQL5Dialect</property>  
  16.         <!– Enable Hibernate’s automatic session context management –>  
  17.         <property name=”current_session_context_class”>thread</property>  
  18.         <!– Disable the second-level cache –>  
  19.         <!–<property name=”cache.provider_class”>org.hibernate.cache.internal.NoCacheProvider</property> 
  20.         –>  
  21.         <!– 配置二级缓存 –>  
  22.         <property name=”hibernate.cache.use_second_level_cache”>true</property>  
  23.         <property name=”hibernate.cache.region.factory_class”>org.hibernate.cache.ehcache.EhCacheRegionFactory</property>  
  24.         <!– hibernate3的二级缓存配置 –>  
  25.         <!– <property name=”hibernate.cache.provider_class”>org.hibernate.cache.EhCacheProvider</property> –>  
  26.         <!– 开启查询缓存 –>  
  27.         <property name=”hibernate.cache.use_query_cache”>true</property>  
  28.           
  29.         <!– Echo all executed SQL to stdout –>  
  30.         <property name=”show_sql”>true</property>  
  31.         <!– Drop and re-create the database schema on startup –>  
  32.         <property name=”hbm2ddl.auto”>update</property>  
  33.         <mapping class=”com.test.pojo.User” />  
  34.     </session-factory>  
  35. </hibernate-configuration>  

 

注意:hibernate4和hibernate3配置不一样,hibernate4是

  1. <property name=”hibernate.cache.region.factory_class”>org.hibernate.cache.ehcache.EhCacheRegionFactory</property>  

 

而hibernate3的配置是

  1. <property name=”hibernate.cache.provider_class”>org.hibernate.cache.EhCacheProvider</property>  

 此处有一个疑问是:hibernate4的官方文档中,已经把class改了,但是属性名称没有改,还是
hibernate.cache.provider_class,不是上面的
hibernate.cache.region.factory_class,但是写成hibernate.cache.provider_class会
报下面错误

 

Java代码 

  1. org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.spi.CacheImplementor]  
  2.     at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:186)  
  3.     at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:150)  
  4.     at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)  
  5.     at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:264)  
  6.     at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790)  
  7.     at com.test.pojo.UserTest.beforeClass(UserTest.java:28)  
  8.     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  
  9.     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)  
  10.     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)  
  11.     at java.lang.reflect.Method.invoke(Method.java:597)  
  12.     at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)  
  13.     at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)  
  14.     at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)  
  15.     at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)  
  16.     at org.junit.runners.ParentRunner.run(ParentRunner.java:300)  
  17.     at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)  
  18.     at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)  
  19.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)  
  20.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)  
  21.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)  
  22.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)  
  23. Caused by: org.hibernate.cache.NoCacheRegionFactoryAvailableException: Second-level cache is used in the application, but property hibernate.cache.region.factory_class is not given, please either disable second level cache or set correct region factory class name to property hibernate.cache.region.factory_class (and make sure the second level cache provider, hibernate-infinispan, for example, is available in the classpath).  
  24.     at org.hibernate.cache.internal.NoCachingRegionFactory.buildTimestampsRegion(NoCachingRegionFactory.java:87)  
  25.     at org.hibernate.cache.spi.UpdateTimestampsCache.<init>(UpdateTimestampsCache.java:62)  
  26.     at org.hibernate.internal.CacheImpl.<init>(CacheImpl.java:72)  
  27.     at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:40)  
  28.     at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:35)  
  29.     at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:91)  
  30.     at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:176)  
  31.     … 20 more  

发表评论

电子邮件地址不会被公开。 必填项已用*标注