How to save a related record in the Bizlet preSave that isn't automatically saved

Viewed 34

We have a Skyve document called NNSF - when an NNSF is created (saved) we need to create a record called a PAM which has an aggregation association to the NNSF.

So in the preSave() we have some code to do this:

PAM pam = PAM.newInstance();
// set a bunch of other attributes
...
// set an association to this NNSF
pam.setNnsf(bean);

The PAM record won't be saved automatically because it's not referenced by the NNSF document, so if we don't explicitly call CORE.getPersistence().save(pam) - the PAM is not saved to the DB even though the NNSF is.

If we do call CORE.getPersistence().save(pam) we get an infinite looping of the preSave() because the PAM has an association to this NNSF.

If we call CORE.upsertBeanTuple(pam) instead, we get FK constraint violation as you would expect, because of the association to the NNSF.

2 Answers

There are a few of approaches to this...

  1. Use an inverseMany in NNSF to PAM with cascade true. This establishes bidirectional relationship PAM has 1 NNSF, NNSF has many PAMs. This allows a cascade save from either direction. The downside is that this can become a drag on performance depending on how many PAMs relate to an NNSF.
  2. Use NNSFBizlet.postSave() to affect the save of the PAM during the save of the NNSF. In postSave() the NNSF is already persisted by the time the PAM is saved. You may need to use either a hand-crafted boolean bean property in NSSFExtension class or a boolean document attribute to control whether to save the PAM in postSave of NNSFBizlet to avoid infinite recursion.
  3. You could upsert the PAM in NSSFBizlet in postSave since the flush of the NSSF has occurred by this event but this would only be useful if the PAM document has no further relations (eg associations or collections).

In this case, turns out it was simple - move the code to the postSave() method.

However, in this case I still needed to calculate whether the creation of the related records needs to occur in preSave(), even though I do the save in postSave()

To do this, you could either create a transient boolean attribute (the option I chose) in the document and store Boolean.TRUE during preSave() (the option I chose), or use a variable in the Extension class.

Related