From de7be3d65d8e43efec05031075ba569e23c60d78 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Mon, 7 Feb 2022 14:11:50 +0100 Subject: [PATCH] Handling JPA Map storage case when parent has been deleted Closes #10033 --- .../listeners/JpaOptimisticLockingListener.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/hibernate/listeners/JpaOptimisticLockingListener.java b/model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/hibernate/listeners/JpaOptimisticLockingListener.java index 1ef3adf677..12dd680c0a 100644 --- a/model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/hibernate/listeners/JpaOptimisticLockingListener.java +++ b/model/map-jpa/src/main/java/org/keycloak/models/map/storage/jpa/hibernate/listeners/JpaOptimisticLockingListener.java @@ -28,6 +28,7 @@ import org.hibernate.event.spi.PreUpdateEventListener; import org.keycloak.models.map.storage.jpa.JpaChildEntity; 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. @@ -46,8 +47,15 @@ public class JpaOptimisticLockingListener implements PreInsertEventListener, Pre Object root = entity; while (root instanceof JpaChildEntity) { 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); } }