【问题标题】:You cannot commit during a managed transaction in Hibernate Criteria您无法在 Hibernate Criteria 中的托管事务期间提交
【发布时间】:2015-09-26 00:50:33
【问题描述】:

早安,

以下是我的原始代码:

Criteria criteria = getSession( ).createCriteria(
                JSNumber.class );
criteria.add( Restrictions.eq( "paymentDate", mnight ) );
JSNumber result = (JSNumber) criteria
                .uniqueResult( );

int newNo = result.getRunningNo( ) + 1;
result.setRunningNo( newNo );
getSession( ).merge( result );
getSession( ).flush( );

这是从 JSNumber 表中获取一个流水号。假设数字是12,然后+1变成13,然后将数据库中的流水号更新为13。

有一个错误是当时间几乎相同时,就在毫秒内,两个请求从/到这个表获取结果/更新,它可能会为两个用户请求返回相同的结果。

例如,第一个请求在 14:47:36.735,第二个请求在 14:47:36.737 第一个请求获取值 = 110,它会更新为 111。但是在第一个请求更新值之前,第二个请求已经获取值,也是 110。

我正在尝试使用beginTransaction() 来处理这种情况。以下是我的新代码:

Transaction tx = null;
tx = getSession().beginTransaction( );

Criteria criteria = getSession( ).createCriteria(
                JSNumber.class );
criteria.add( Restrictions.eq( "paymentDate", mnight ) );
JSNumber result = (JSNumber) criteria
                .uniqueResult( );

int newNo = result.getRunningNo( ) + 1;
result.setRunningNo( newNo );
getSession( ).merge( result );
getSession( ).flush( );

tx.commit( );

这将命中java.sql.SQLException: You cannot commit during a managed transaction!

我是 Hibernate 的新手。请告知我犯了什么错误。我尝试谷歌很长时间,但似乎找不到我理解的方法。

【问题讨论】:

  • 你能分享你的hibernate配置(xml)吗?
  • 将这段代码包装在一个事务中并没有帮助,因为这本身并不会阻止另一个事务读取旧值。这不是一个容易解决的问题;谷歌“丢失更新问题”。

标签: java database hibernate transactions criteria


【解决方案1】:

您的交易有可能 正在由其他休眠(很可能是容器)管理。
这就是例外。
在这些托管环境的情况下,Hibernate 无法自行处理事务。 由该托管环境完成的事务处理(开始、提交或回滚数据库事务)。

请阅读transactions-demarcation了解清楚原因

【讨论】:

  • 有什么办法可以解决我的问题吗?我的意思是There is a bug which is when the time is almost the same, just within millisecond , two request to get result/update from/to this table, it may return same result for both's user request.,正如我提到的那样。
  • 绝对有办法。你能用你的休眠配置xml更新你的问题吗?
猜你喜欢
  • 2023-03-28
  • 2015-06-28
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 2014-06-16
  • 2014-09-20
  • 1970-01-01
相关资源
最近更新 更多