Associated entity is deleted -> duplication of parent entity throws exception

To show the case I made a minimum project: (99.7 KB)

If you create a Entity2, then create a ParentEntity with an association to Entity2, then delete Entity2 and use the duplicate Button in the ParentEntity Browser you will get the following error:

IllegalStateException: An attempt to save an entity with reference to some not persisted entity. All newly created entities must be saved in the same transaction. Put all these objects to the CommitContext before commit.

The error is misleading here IMHO, the problem is, that an associated entity is already deleted.
The code from the duplicate method looks like this:

    public ParentEntity duplicate(ParentEntity entity) {
        ParentEntity duplicated = dataManager.create(ParentEntity.class);
        return dataManager.commit(duplicated);

I’m not sure if this is a platform bug, but I guess it is. A workaround would be to check every association before with entityStates.isDeleted, but I’d prefer not to. :wink:

This is a known limitation of the soft deletion mechanism.
You cannot persist a new entity that references other soft-deleted entities through x-to-one relations.

Note that from the business point of view such thing doesn’t make much sense. The Entity2 has been soft-deleted, it’s already hidden from all tables and option lists. User wouldn’t be able to select such instance as an option for the association.

The exception message is a little misleading though.

Hi @albudarov, thanks for your answer, I get that. Duplication of entities is a common task, and entities having a soft-deleted reference as well I guess, so do you know of a better way of doing the duplication?

Duplicating an entity with a reference to a soft-deleted entity is a invalid thing from a business point of view.

Imagine a situation:

  • You have Product entity “Bread”
  • You create Order entity “#115” referencing Bread.
  • Then you soft-delete Bread.
  • Then you try to duplicate entity #115.

Creating new order referencing deleted Bread is a non-sense business operation, because this product no longer exists.

I suppose, when doing the duplication, you should check for soft-deleted references. Then clear them. If they are required attributes, show an editor screen to the user asking to specify missing attributes.