StaleStateException when saving entity with complex relations

前端 未结 2 1089
忘掉有多难
忘掉有多难 2021-01-02 20:06

The hibernate entity I am saving in the database (Oracle) has very complex relations, in the sense that it has many related entities. It looks something like this...

<
相关标签:
2条回答
  • 2021-01-02 20:52

    This happened to me under the following circumstances:

    • I created objectA in java code.
    • I added extant objectB to objectA as a field. objectB has a one to one relation with objectA.
    • I saved(created) objectA in the database.
    • When objectA was saved, objectB was updated in the database to add the id of objectA.

    • Then I added an objectC to objectA (one objectA for many objectCs). I tried to update objectA and got the stalestateexception....even when using merge.

    The answer is that I needed to either update objectB or retrieve a fresh istance of objectA from the database

    0 讨论(0)
  • 2021-01-02 21:11

    The error can be caused by several things:

    1. Flushing the data before committing the object may lead to clear all object pending for persist.
    2. If object has primary key which is auto generated and you are forcing an assigned key
    3. if you are cleaning the object before committing the object to database.
    4. Zero or Incorrect ID: If you set the ID to zero or something else, Hibernate will try to update instead of insert.
    5. Object is Stale: Hibernate caches objects from the session. If the object was modified, and Hibernate doesn’t know about it, it will throw this exception — note the StaleStateException

    I'm not taking the credit for it, found it here.

    0 讨论(0)
提交回复
热议问题