Search code examples
javahibernatejpajpql

Find base entity name from jpql


I have a jpql and would like to find the alias for the base entity given in the jpql at run time. is it possible?

eg SELECT home FROM HomeEntity home WHERE homeId IS NOT NULL;

i would like to find out the alias, in this case "home" from the query before executing it so that I can modify the query at run time like add an ORDER BY home.createdDate to the jpql before it is executed.


Solution

  • I ended up parsing the JPQL and pulling out the base entity alias using regex. Below is the code. Feel free to use it or improve it or provide suggestions. private String findBaseEntityAliasFromJPQL(String jpqlString) {

        String baseEntityAlias = null;
        Pattern pattern = Pattern.compile("SELECT.+?FROM.+?\\w+?\\s+?(\\w+)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(jpqlString);
        if (matcher.find()) {
            baseEntityAlias = matcher.group(1);
        }
        Assert.hasText(baseEntityAlias, "Not able to find the base Entity Alias for the JPQL Query=" + jpqlString);
        return baseEntityAlias;
    }