Hibernate性能优化

1、性能是与具体的项目挂钩的,并不是对于A项目某种优化方法好就适用于B项目、性能需要不断的测试检验出来的.....(废话)

2、session.clear()方法的使用,通常session是有缓存的 在一个session不关闭时 不断的取数据,数据会不断的往缓存里面添加,到达一定程度时出现内存溢出的情况,

  这也是由于程序逻辑不当造成的一种内存泄露问题,在使用同一个session取数据的时候最好使用session.clear清除一下数据在取,防止内存泄露

3、hibernate的list和iterate方法的区别:list方法每次都会去数据库取,iterate 首次会取出每条记录的主键,用到的时候会按照主键去数据库中取出

4、1+N问题:在一对多关联问题上 我想取出所有多的方的数据 不需要取出一方数据 ,因为默认是eager,所以会触发1+N问题,现在有三种方法解决

  1> fetchType.lazy

  2>batchSize(size)(不正规)

  3>left join fetch 

5、二级缓存sessionfactory

  1>配置hibernate.cfg.xml ssh整合的话可以在applicationContext.xml中配置

  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        p:dataSource-ref="dataSource" p:mappingLocations="classpath*:/com/**/*.hbm.xml">
        <property name="packagesToScan">
            <list>
                <value>com/</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</prop>
            </props>
        </property>
    </bean>

 2>引入jar包ehcache-2.8.3.jar    ehcache-core-2.4.3.jar  ehcache-web-2.0.4.jar

 3>引入xml文件 ehcache.xml

 4>使用  注解方式 @Cache(usage=CacheConcurrencyStrategy.READ_WRITE)

原文地址:https://www.cnblogs.com/Wen-yu-jing/p/4107523.html