项目中使用了Hibernate,在要测试之前将应用部署到客户测试环境中时发现程序响应明显缓慢,经查后发现Hibernate的级联加载大大加大了响应时间,在加入了二级缓存(我用的是ehcache)后,发生了一系列问题,现做个记载
引用:
Spring Hibernate SessionFactory相关配置:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.Oracle9Dialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider </prop> <prop key="hibernate.jdbc.batch_size">20</prop> <prop key="hibernate.cache.use_second_level_cache"> true </prop> <prop key="hibernate.connection.provider_class"> org.hibernate.connection.C3P0ConnectionProvider </prop> </props> </property>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref local="sessionFactory" /> </property> <property name="cacheQueries"> <value>true</value> </property> </bean>
<prop key="hibernate.cache.use_query_cache">true</prop>
<property name="cacheQueries">
<value>true</value>
</property>
以上是开启了查询缓存
怎么配置实体缓存请google
Ehcache配置:
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <diskStore path="java.io.tmpdir" /> <!-- 缓存最大数目 --> <defaultCache maxElementsInMemory="1000" eternal="false" overflowToDisk="true" timeToIdleSeconds="180" timeToLiveSeconds="360" /> <cache name="org.hibernate.cache.UpdateTimestampsCache" maxElementsInMemory="5000" eternal="false" timeToIdleSeconds="180" timeToLiveSeconds="360" overflowToDisk="false"/> <cache name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="180" timeToLiveSeconds="360" overflowToDisk="false"/> <cache name="com.sinotrust.entity.data.DataDir" maxElementsInMemory="500" eternal="true" overflowToDisk="false" timeToIdleSeconds="180" timeToLiveSeconds="360" /> <cache name="com.sinotrust.entity.ras.RasDicCodemanager" maxElementsInMemory="700" eternal="true" overflowToDisk="false" timeToIdleSeconds="180" timeToLiveSeconds="360" /> <cache name="com.sinotrust.entity.ras.RasDicCatalog" maxElementsInMemory="100" eternal="true" overflowToDisk="false" timeToIdleSeconds="180" timeToLiveSeconds="360" /> <cache name="com.sinotrust.entity.ras.RasSysMenuconf" maxElementsInMemory="50" eternal="true" overflowToDisk="false" timeToIdleSeconds="180" timeToLiveSeconds="360" /> </ehcache>
问题1:实体新增后通过级联方式获取不到新增内容
原因是因为我在新增时没有在关联对像的set集合里加入新增的对像因此集合内和数据库是不同步的
解决:在新增时,设置相关实体的引用关系。
问题2:修改关联时原先关联方还是保有修改对像
解决:在修改时,先将原先关联方引用解除,再设置新的关系