Handling JPA Map storage case when parent has been deleted

Closes #10033
This commit is contained in:
Alexander Schwartz 2022-02-07 14:11:50 +01:00 committed by Hynek Mlnařík
parent f78b8bf89f
commit de7be3d65d

View file

@ -28,6 +28,7 @@ import org.hibernate.event.spi.PreUpdateEventListener;
import org.keycloak.models.map.storage.jpa.JpaChildEntity; import org.keycloak.models.map.storage.jpa.JpaChildEntity;
import javax.persistence.LockModeType; import javax.persistence.LockModeType;
import java.util.Objects;
/** /**
* Listen on changes on child entities and forces an optimistic locking increment on the topmost parent aka root. * Listen on changes on child entities and forces an optimistic locking increment on the topmost parent aka root.
@ -46,8 +47,15 @@ public class JpaOptimisticLockingListener implements PreInsertEventListener, Pre
Object root = entity; Object root = entity;
while (root instanceof JpaChildEntity) { while (root instanceof JpaChildEntity) {
root = ((JpaChildEntity<?>) entity).getParent(); root = ((JpaChildEntity<?>) entity).getParent();
Objects.requireNonNull(root, "children must always return their parent, never null");
}
// a session would not contain the entity if it has been deleted
// if the entity has been deleted JPA would throw an IllegalArgumentException with the message
// "entity not in the persistence context".
if (session.contains(root)) {
session.lock(root, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
} }
session.lock(root, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
} }
} }