spring jpa @version 在事务未提交之前自动更新版本。

huangapple go评论56阅读模式
英文:

spring jpa @version auto update version before transaction uncommited

问题

以下是您的代码。Acct对象具有一个名为version的字段,并且我使用了@version注释。

我猜这是因为我没有提交事务。

它生成了脏数据。

之后,当我查询同一张表的数据库时,JPA会自动更新脏数据的版本。

但是除了版本字段之外,其他字段没有更新,这让我感到困惑。

saveFlush将解决这个问题,但它太慢了!

英文:

below is my code. Acct Object has a field version and I used the @version annotation.

I guess because I am not committed the transaction.

it generated dirty data.

and after I query the database for same table.

jpa auto update the dirty data's version.
but besides version field. other field was not update.it make me fell confuses

saveFlush will solve the proble. but it is too slow!

// open transaction
            Acct acct = acctRepository.findByAcctNo("a");
            System.out.println("version1:" + acct.getVersion()); // 1
            for(int i = 0; i < 100 ; i ++) {
                acct.deposit(BigDecimal.ONE);
            }
        
            System.out.println("version2:" + acct.getVersion()); // 100  
            Acct acctOther = acctRepository.findByAcctNo("b");
            
            System.out.println("version3:" + acct.getVersion()); // 2  other info is equal with version2
// commit transaction

答案1

得分: 0

  • 问题可能在于您在 acct.deposit(BigDecimal.ONE) 内部增加了 acct.version。因此,它变成了 100。

  • 但是您不应该自行增加 version 字段,Hibernate 会在更新操作的刷新期间自动增加它。

  • Hibernate 还会在执行 acctRepository.findByAcctNo("b") 之前自动刷新会话中迄今为止的所有内容。在刷新时,它会忽略您手动对 account.version 进行的每个更新,并根据会话中的内容自动增加它。在其会话中,它会记住,它给了您版本 1,因此将其增加到 2 并进行刷新。在刷新之前,它将重置您设置的不正确的版本。

英文:
  • Your problem is you are probably incrementing the acct.version inside the acct.deposit(BigDecimal.ONE). So it becomes 100

  • But you are not supposed to increment version field yourself and hibernate will automatically increment it during flush of update operation.

  • Hibernate also auto flush whatever so far in the session just before executing acctRepository.findByAcctNo("b"). When it flushes, it ignores every update you manually did to account.version and just auto increments it based what it has in its session. In it's session, it will remember, it gave you version 1 and so it increments it by 1 to 2 and flushes it. Just before flushing, it would have reset the incorrect version you put

huangapple
  • 本文由 发表于 2020年7月31日 15:17:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63187398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定