RemoteException: Cannot merge an Entity that has been removed

Hello,

I’m trying to make a method inside a bean, that get’s called periodically to clean the DB from the soft-deleted entities older than a day, let’s say.

        Collection<MetaClass> metaClasses = metadata.getClasses();

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, -1);

    CommitContext commitContext = new CommitContext();
    commitContext.setJoinTransaction(true);
    commitContext.setSoftDeletion(false);

    metaClasses.forEach(metaClass -> {
        List<Entity<Object>> list = transactionalDataManager.load(metaClass.getJavaClass())
                .query(
                        "select e from " + metaClass.getName() + " e " +
                                "where e.deleteTs is not null" +
                                "and e.deleteTs < :date"
                )
                .parameter("date", calendar.getTime())
                .softDeletion(false)
                .list();

        commitContext.getRemoveInstances().addAll(list);
    });

    EntitySet entitySet = dataManager.commit(commitContext);
    log.info("Successfully deleted " + entitySet.size() + " entities .");

This is the method that does all the magic, but at the dataManager.commit(commitContext) line, I get the following exception:
remove-issue.txt (10.8 KB)

Why can this happen?

Thank you,
Alex

3 Likes

Hi Alex,

It looks like the same object appears in the commit context twice.
Try to debug or print the collected entities before dataManager.commit().

Regards,
Konstantin

Hello Konstantin,

How is it possible to find duplicates in a HashSet?

This is hardly possible, I agree.
But I can imagine a situation when you have an eager fetching and cascade delete on the JPA level, which could lead to the error.

I’m pretty sure this is the case. Do you have a suggestion for how can I deal with such a case?

We don’t recommend using JPA eager fetching and cascade operations, it is explicitly stated in the docs.

I misunderstood your first statement, we do NOT use JPA cascade annotations anymore, we use only the @OnDelete and @OnDeleteInverse annotations provided by the platform.

I cannot reproduce the error using a relationship with the normal @OnDelete instruction. Also, the stack trace shows that the error occurs long before the cascade deletion mechanism.
Can you attach the net.kprism.scope.foundation.entity.measure.Quantity entity class and all entities it is connected to?