Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Session is invalidated after ConstraintViolationException

Tags:

hibernate

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:

    Parent other=service.load(33); // loads a new parent
    try {
        Parent p=new Parent();
        p.setName("A name");
        service.save(p); // a @Transactional spring service class, throws ConstraintViolationException - name should be at least 15 characters long
    } catch (ConstraintViolationException e){
        // i would like to handle validation errors and proceed normally
        // but the session is allready closed here
    }
    System.out.println("Children: " + other.getChildren()); // lazy initialization exception, even when using opensessioninview

From now on the hibernate session is completely useless, even for read-only operations like rendering a lazy collection in view using OpenSessionInView pattern.

like image 733
Pma Avatar asked Feb 24 '11 18:02

Pma


1 Answers

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.

like image 184
esaj Avatar answered Sep 19 '22 16:09

esaj