I discovered a weird behavior working in KEYCLOAK-18842. The main problem in that JIRA is that there is a bug in mariadb/mysql that makes a delete with a subquery terribly slow (MDEV-21012). I was trying to just use the addNamedQuery method to replace that named query with a native implementation for those engines at runtime/startup. But it doesn't work because it seems that the NamedQueryRepository stores them in two different maps and the jpql one is always tried first when the createNamedQuery method is called. Reading the javadoc for the addNamedQuery I think this is a bug, replacing a jpql query with a native one is impossible right now.
I implemented a tentative fix for this with this commit. There is a test which exemplifies the problem better than this description.