Error deleting imported users via Java API

Hi Everyone,

The following is code to delete users imported via a UserStorageProvider:

            KeycloakSession session = this.factory.create();
            session.getContext().setRealm(this.realm);

            try {
                session.getTransactionManager().begin();
                String providerId = this.realm.getId();

                List<UserModel> importedUsers = session.users()
                .searchForUserStream(realm, Collections.singletonMap("federationLink", 
                providerId), null, null)
                .collect(Collectors.toList());
                for (UserModel user : importedUsers) {
                    session.users().removeUser(realm, user);
                    logger.infof("Removed user: %s", user.getUsername());
                }

                session.getTransactionManager().commit();
            } catch(Exception e) {
                session.getTransactionManager().rollback();
                logger.error("Failed to remove imported users, rolled back", e);
            }

I am getting the following, intermittent error:

ERROR [keycloak.userstorage.RemoveImportedUsers] (pool-3-thread-1) Failed to remove imported users, rolled back: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.keycloak.models.jpa.entities.RealmEntity.components: could not initialize proxy - no Session

Any ideas on how to fix this?

–John

would this be the way to fix:

KeycloakModelUtils.runJobInTransaction(factory, (KeycloakSession session) -> {
        RealmModel realm = session.realms().getRealm("myRealm");
      });

wow, it worked once (deleted user) and then next time it failed on this exact code:

I wonder if it’s because I create the session and then try to load all the components?

appears to be a race condition, because it works sometimes and fails others w/ no discernible pattern

Can you tell where is the race condition happens? So we can log it to identify it in the future, wether we lock the record or do something else