shh框架使用链接池出现不释放的问题
基本上都是未关闭链接池的资源导致的,一般有以下情况:
1.未使用事务时session未手动关闭
//Configuration接口负责配置并启动Hibernate,创建SessionFactory对象。
Configuration configuration=new Configuration().configure();
//.SessionFactory接口负责初始化Hibernate。 其实就是连接数据库的
SessionFactory sessionFactory=configuration.buildSessionFactory();
//.持久化工具session
Session session=sessionFactory.openSession();
Query query2 = session.createQuery(“from Orders”);
List list = query.list();
//关闭资源
session.close();
最后一定要有session.close(); 来关闭资源,表示操作完成,释放当前所持有的连接池。
###1.使用事务时session不自动关闭
事务都配好了,但是连接池还是很快就达到上限,比如c3p0在进行15次操作后就开始等待响应(连接池未释放,c3p0默认最大15)。
spring中事务注解配置:
<context:annotation-config/>
<!-- 扫描包设置 -->
<context:component-scan base-package="com.zrrd.*"/>
<!-- tx:advice和 切点的替代法-注解-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 定义事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
事务一般在service层配置
//该方法及其相关方法开启事务
@Transactional(readOnly=false)
public void addStudent(Student student, int[] trId) {
// TODO Auto-generated method stub
studentDao.addStudent(student,trId);
}
dao层添加方法
public void addStudent(Student student, int[] trId) {
Session session=sessionFactory.openSession();
Set<Teacher> set=new HashSet<Teacher>();
for(int id:trId){
Teacher teacher =(Teacher)session.get(Teacher.class, id);
set.add(teacher);
}
student.setTeachers(set);
session.save(student);
}
以上程序在执行15次添加后会出现连接池不释放,浏览器一直请求的现象。出现该情况的原因是由于使用的session获取方式为openSession()。
正确的方式时使用:
Session session=sessionFactory.getCurrentSession();
两者的区别在于:
getCurrentSession创建的session会和绑定到当前线程,而openSession不会。
getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而openSession必须手动关闭
简单来说就是使用openSession,spring框架的事务就默认不会管理session,而使用getCurrentSession时,spring的事务就会管理session,从而在方法结束时关闭session,使得连接池释放。这样一般就不会出现链接池达到上限了。
当然,如果你使用的是lazy(懒加载)
你就须延长session生命周期到view,也就是前台显示页面,因为事务默认在该方法结束时关闭session,也就是在dao层关闭,如果不延长生命周期view将取不到值。
方法是在web.xml中配置filter,如下:
<!-- OpenSessionInViewFilter过滤器需要配置在Struts2框架过滤器前面,否则不起作用。 -->
<filter>
<filter-name>openSession</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
以上类容为个人见解,不足之处请指出。