简体   繁体   中英

How to join on unnest columns using JPQL?

I have a simple query that I'd like to translate to JPQL / Hibernate. I'm using Postgres 14.

select unnest(cast('{hello, world}' as text[]));

The real query is a bit more complicated and will use the new column and join it with existing columns.

I'm currently using a nativeQuery but ideally I'm able to get rid of it. So I tried a few things but couldn't find a solution.

First of all I tried to register unnest as a function.

public class Contributor implements MetadataBuilderContributor {
    @Override
    public void contribute(MetadataBuilder metadataBuilder) {
        metadataBuilder.applySqlFunction(
            "unnest",
            new StandardSQLFunction("unnest", StandardBasicTypes.CHARACTER_ARRAY)
        );
    }
}

Nevertheless I'm getting the error

antlr.MismatchedTokenException: expecting CLOSE, found '['

Looks like there is an issue with cast() . So I tried something simpler just to check the syntax.

@Query("select unnest(:vals)")
List<MyDTO> hello(List<String> vals);

Here I'm getting another error.

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected end of subtree

I tried more variations and also something like function('unnest', :vals) but nothing worked.

Any ideas how to make it work? Thank's a lot!

i had the same problem as you but with a List<Integer> , the only solution that worked for me is to transform the List<Integer> to a String then in the native query i used unnest(string_to_array(:ids,',')\\:\\:integer[])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM