2

Hello I have a question about beforeInsert/beforeUpdate in Grails. I can't get a simple parent/child use case to work. The child updates the parent grandchildren counter. See the model below:

  class Parent{
      int grandchildren

      def beforeUpdate(){

      }
  }

  class Child{
      Parent parent
      int childCount

      def beforeInsert(){
          // 1: Works, beforeUpdate is called in Parent
          parent.grandchildren+=childCount
          parent.save()
      }

      def beforeUpdate(){
          // 2: Does not work, grandchildren not updated and beforeUpdate not called in Parent
          parent.grandchildren+=childCount
          parent.save()
      }
  }

2) This is documented by the grails documentation. BeforeUpdate is called while the session is flushing thus adding a update while updates are being handled leads to unexpected behaviour. The documentation says to use withNewSession to workarround this, but I can't figure out to do this without having the parent instance registered in two different sessions.

My question is how to implement this. I don't want to use HQL to update the parent entity, because I need beforeUpdate to be called.

Dennie de Lange
  • 2,776
  • 2
  • 18
  • 31
  • why before and not after ? why does it need to happen before ? – V H Mar 13 '17 at 14:29
  • it does not make a difference in this example. I use beforeUpdate, because it allows access to isDirty.. But if you can show me how to do this with afterUpdate it would suffice for me. – Dennie de Lange Mar 13 '17 at 21:54
  • http://stackoverflow.com/questions/14248783/weird-afterinsert-afterupdate-loop-in-grails http://stackoverflow.com/questions/9633932/beforeupdate-afterupdate – V H Mar 13 '17 at 22:17
  • Thanks, for these posts, but this is not what I want. The example code is specific for my needs, and it looks trivial. Parent does not know of the child, but a change of parent in the beforeUpdate/afterUpdate of Child should trigger the beforeUpdate of parent. – Dennie de Lange Mar 13 '17 at 22:58

0 Answers0