How do I clear and replace a collection in a one-to-many relationship in Grails/Groovy

前端 未结 4 685
耶瑟儿~
耶瑟儿~ 2021-02-14 06:13

This question is in two parts, first part is about clearing a list and second part is about assigning an owner to an object.

I have a one-to-many relationship between tw

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-14 06:51

    While this is an older question, I ran into a very similar situation in which I wanted to update a set of child records. Here's how I chose to resolve it. For simplicity, I'll use the same object/relation names as the asker of the question.

    1. In the mapping block of the parent domain, add:

      static mapping = {
          locations(cascade: "all-delete-orphan")
      }
      
    2. In the child domain, add the @EqualsAndHashCode annotation (just in case there's another one lurking about, I'm referring to groovy.transform.EqualsAndHashCode).

    3. Add all of the children elements to the parent domain using the Grails addTo methods (e.g. addToLocations) and then save the parent domain.

    While this approach does require saving the parent domain (which the asker didn't want to do), it seems like it's the most appropriate approach given the clear belongsTo definition in the model. I would therefore answer the asker's numbered questions like this:

    1. Rather than doing it manually, let Grails/Hibernate clear the records by specifying the all-delete-oprhan cascade behavior on the relation.

    2. Don't attempt to save the child records directly, but instead save the parent object to match what Grails seems to expect.

提交回复
热议问题