spring定时器时batch批量操作出现找不到session的解决办法

在Spring定时任务Quartz中执行batch更新操作时遇到找不到Session的错误,通过Session session = sessionFactory.openSession()初始化Session并使用SessionFactoryUtils获取数据库连接。在遍历并更新未支付订单时,确保事务正确管理,避免并发和数据一致性问题。当订单未支付时间超过预设间隔(如2小时),更新订单状态为已关闭。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<pre name="code" class="java">Session session = sessionFactory.openSession();
获取session 解决了找不到session的问题。

/**
	 * @Title: batchUpdateOrder
	 * @Description: 未支付超过2小时,订单关闭
	 * @param: @return  设定文件
	 * @return: Integer  返回类型
	 * @throws
	 */
	public Integer batchUpdateOrder(){
		Integer result=0;
		
		Connection conn = null; 
		PreparedStatement pstmt = null; 
		ResultSet rs=null;
		//未支付订单集合
		
		//超过2个小时未支付,订单自动关闭
		String sql="update order_details d,order_master_info m set d.order_status=4,m.order_status=2 "+
                " where d.order_master_id=m.id and d.id=0 ";
        //遍历分销商,保存到分期账单表中		
		try{	
			Session session = sessionFactory.openSession();
			conn = SessionFactoryUtils.getDataSource(sessionFactory).getConnection(); 
			conn.setAutoCommit(false); 
			pstmt = conn.prepareStatement(sql); 
			
			String sqls="select * from order_details where order_status=0";
			List<OrderDetails> detailList=session.createSQLQuery(sqls).addEntity(OrderDetails.class).list();
			
			for(OrderDetails order:detailList){
				//现在时间 - 订单创建时间>=2
				Date currentDate=new Date();
				Long time1=currentDate.getTime()-order.getCreateDate().getTime();
				long nh = 1000*60*60;//一小时的毫秒数
				long hour = time1/nh;//计算差多少小时
				
				conn.setAutoCommit(false); // 开始事务    
				//系统配置支付间隔数
				Integer payInterval=SystemConfigUtil.getSystemConfig().getOrderPayInterval();
				if(payInterval.equals(null) || payInterval==0){
					payInterval=2;
				}
				if(hour>=payInterval){
					pstmt.setInt(1, order.getId());    
				}
				pstmt.addBatch();  
			} 
			pstmt.executeBatch(); 
			conn.commit(); 
			conn.setAutoCommit(true); 
		} catch (SQLException e) { 
			if (conn != null) { 
				try { 
				conn.rollback(); 
				} catch (SQLException e1) { 
				e1.printStackTrace(); 
				} 
			} 
		} finally { 
			if (pstmt != null) { 
				try { 
				pstmt.close(); 
				} catch (SQLException e) { 
				e.printStackTrace(); 
				} 
			} 
			if (conn != null) { 
				try { 
				conn.close(); 
				} catch (SQLException e) { 
				e.printStackTrace(); 
				} 
			} 
		} 
		return result;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值