How to recover from `don't flush the Session after an exception occurs` error?

前端 未结 2 1495
旧巷少年郎
旧巷少年郎 2021-02-04 19:42

I have two classes :

User

class User {
    //relationships. . . .
    static belongsTo = [ company : Company, role : Role ]
    static          


        
2条回答
  •  一个人的身影
    2021-02-04 20:35

    The reason that you are getting this error is that when the statement Role.findBy static method is executed, Hibernate(which is used by grails GORM) checks whether "autoFlush" is required. Since new transient Role objects are present, Hibernate tries to automaically flush the session. However at this point the new user objects are present which haven't yet been associated with a role (which is not nullable in User domain). Therefore while flushing, the user object doesn't pass the validation and hence has a null id as mentioned in the exception.

    The way to solve this would be to make all the DB read calls (such as findBy methods) before you start creating/updating entities of the same type.

    Another option (although not a very good one ) is to set the session flush mode manual.

        User.withSession{ sessionObj ->
            sessionObj.setFlushMode(FlushMode.MANUAL);
            //put your Role.findBy mthod call here
            sessionObj.setFlushMode(FlushMode.AUTO);
    
        }
    

提交回复
热议问题