解决hibernate产生的id序列或者setXX不能同步到数据库到问题(this.hibernateTemplate.flush();hibernateTemplate.getSessionFactory().getCurrentSession().connection().commit())

通过WarehouseInventoryPreLog warehouseInventoryPreLog = new WarehouseInventoryPreLog();产生一个id序列

如果不flush(),那么数据库里就暂时没有这个值

-->hibernate的实体都是存储在缓存中的,
   所以你会发现有的时候当你创建出两个主键相通的实体的时候会报错。
   正常情况是当你调用save方法的时候,这个实体对象未必已经保存到数据库了,
   调用close方法的时候,对象才真正保存如数据库。当你调用flush方法的时候是强制将对象保存到数据库。
	if ("xs005".equalsIgnoreCase(logisticsOrderType.getTypeCode())
				|| "xs001".equalsIgnoreCase(logisticsOrderType.getTypeCode())) {
		// 锁定库存预分配,物流单类型是选择仓库的。
			Long warehousId = logisticsOrders.getFromWarehouseId().getId();
			Long customerId = logisticsOrders.getCustomerInfoByOwnerId()
					.getId();
			//callProcedureManualArrange(warehousId, customerId, newStr); //here is the problem !!!!
			WarehouseInventoryPreLog warehouseInventoryPreLog = new WarehouseInventoryPreLog();
			this.hibernateTemplate.save(warehouseInventoryPreLog);
			this.hibernateTemplate.flush();
			Long preLogId = warehouseInventoryPreLog.getId();
			callProcedureManualArrangeForPreLog(warehousId, customerId, newStr, preLogId);
		}

 一个好几天到问题,hibernate不能读到高位值,导致锁表,原因是数据库产生主键值 和hibernate的hilo机制不同步,要在调用完存储过程后使用 hibernateTemplate.getSessionFactory().getCurrentSession().connection().commit(); 但是flush()不行。

	hibernateTemplate.update(salesOrders);
		//hibernateTemplate.flush();  //不好用
		hibernateTemplate.getSessionFactory().getCurrentSession().connection().commit();//如果没有,前面数据库产生id和下面save冲突 
		// 保存订单操作日志
		salesOperationProcessService.saveSalesOperationProcess(salesOrders,
				SalesOrderFlowServiceImpl.toDeliver.getId(),
				OrderConstant.LOG_ORDER_MANUAL_ARRANGE_SUBMIT,
				Constant.OPERATION_TYPE_POSITIVE, null, null);

 放在update后面是为了防止出错回滚,放在update前面就无法回滚

原文地址:https://www.cnblogs.com/kyxyes/p/3553295.html