Hibernate Session is invalidated after ConstraintViolationException

前端 未结 2 1209
無奈伤痛
無奈伤痛 2021-01-02 08:10

Is there any way to continue using an thread bound hibernate session after constraintviolation exception has been thrown? I\'m giving a short example here:

          


        
相关标签:
2条回答
  • 2021-01-02 08:39

    Use a StatelessSession instead of a Session. That is the trick.

    With a StatelessSession you can continue after any exceptions as it is possible in SQL (even inside one transaction - no commit/rollback is done by hibernate). That is ideal for bulk updates/inserts or for checking if unique constraints are violated.

    But beware, a StatelessSession has many Restrictions compared with a normal session. Please refer to the Hibernate documentaion / Javadocs for that.

    0 讨论(0)
  • 2021-01-02 08:52

    Session's documentation states that If the Session throws an exception, the transaction must be rolled back and the session discarded. The internal state of the Session might not be consistent with the database after the exception occurs..

    AFAIK, there's no way to recover from this, I recall someone at work warning me not to use the session-per-request/OpenSessionInView-pattern because of these kinds of problems.

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