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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值