Saving programmatically created composition items

I have written the following code to create new composition entities following this user guides:

  @Subscribe("bankCashEntryApTable.create")
    public void onBankCashEntryApTableCreate(Action.ActionPerformedEvent event) {
        BankCashEntryAp bankCashEntryAp = metadata.create(BankCashEntryAp.class);
        bankCashEntryAp.setBankCashEntry(getEditedEntity());
        bankCashEntryAp.setAmountPaid(0.0);
        bankCashEntryAp.setAmountBalance(0.0);
        bankCashEntryApDc.getMutableItems().add(bankCashEntryAp);

        // set focus on the first cell of the added row
        bankCashEntryApTable.scrollTo(bankCashEntryAp);

        // set focus on the first cell of the added row
        bankCashEntryApTable.setSelected(bankCashEntryAp);
        bankCashEntryApTable.requestFocus(bankCashEntryAp, "apInvoice");
    }

However, when I save it, it throws the following exception:

IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: com.inteacc.pf.entity.BankCashEntryAp-220cb532-0a0d-46e1-662f-5252dd0a683f [new].

Used dataContext instead of metadata then worked.

If the entity is created through ‘metadata.create’ - it is not associated with the ‘dataContext’ of this screen.
Simply adding such an entity to a container is not enough.
You need to use binding to dataContext as described in the documentation:(Entities :: Jmix Documentation)
DataContext :: Jmix Documentation

Or use DataContext.create() instead of metadata.create.
https://docs.jmix.io/jmix/data-model/entities.html#instantiation

3 Likes