hibernate中session增删改操作及事务提交的问题

一、问题回顾

Session session = MySessionFactory.getSession();
//		Transaction tx = null;
//		try{
//			String hql="delete form td_report where ID=1" ;
//			tx = session.beginTransaction();
//			Connection con=session.connection();
//			PreparedStatement stmt=con.prepareStatement(hql);
//			stmt.executeUpdate(hql);
//			tx.commit();
//			con.close();
//		}catch(Exception ex){
//			if(tx!=null)tx.rollback();
//			ex.printStackTrace();
//		}finally{
//			MySessionFactory.closeSession();
//		}
<!-- 配置C3P0连接池属性 -->
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">5</property>
<!-- 最大空闲时间,3600秒内未使用则连接被丢弃。若为0则永不丢弃。默认值: 0-->
<property name="hibernate.c3p0.timeout">3600</property>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
			属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
			如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<!-- 最大的PreparedStatement的数量 -->
<property name="hibernate.c3p0.max_statements">100</property>
<!-- 每隔3000秒检查连接池里的空闲连接 ,单位是秒 默认0-->
<property name="hibernate.c3p0.idle_test_period">3000</property>

 导致结果:td_report表一直被锁住,其他数据库连接一直操作不了,系统崩溃。

二、问题原因

//			Connection con=session.connection();
//			PreparedStatement stmt=con.prepareStatement(hql);
//			stmt.executeUpdate(hql);

导致数据库连接中PreparedStatement不在次会话(session)当中,会一直等待当前会话事务提交。

三、解决办法

第一种:修改配置文件

<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
			属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
			如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
		<!-- 最大的PreparedStatement的数量 -->
		<property name="hibernate.c3p0.max_statements">0</property>

hibernate.c3p0.max_statements=0,牺牲查询速度(PreparedStatement提高下次查询速度效率)降低代码事务死循环。

第二种:修改代码

Session session = MySessionFactory.getSession();
		Transaction tx = null;
		try{
			String hql="delete from td_report where ID>0 and creater='"+loginname+"' ";
			tx = session.beginTransaction();
			Query query = session.createSQLQuery(hql);
			query.executeUpdate();
			tx.commit();
		}catch(Exception ex){
			if(tx!=null)tx.rollback();
			ex.printStackTrace();
		}finally{
			MySessionFactory.closeSession();
		}
Session session = MySessionFactory.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.delete(report);
			tx.commit();
		} catch (Exception ex) {
			if (tx != null)
				tx.rollback();
			ex.printStackTrace();
		} finally {
			MySessionFactory.closeSession();
		}

本文原文地址:https://blog.csdn.net/zhangjq520/article/details/84955911

猜你喜欢

转载自blog.csdn.net/Roger_CoderLife/article/details/85228462