1

in postgres we can use the following construct to create a temporary table of type array of integers. For example the singleTestColumn below. Usually this is used during CTE.

String sql_query = "SELECT  ARRAY[]::INTEGER[] AS singleTestColumn";

How to properly map this column in hibernate native sql query.

taking into account the custom integer array mapping described here https://vladmihalcea.com/how-to-map-java-and-sql-arrays-with-jpa-and-hibernate/#comment-26149 i.e. by that i mean the IntArrayType class.

        Query<Object[]> query = session.createNativeQuery(sql_query)
                .addScalar("singleTestColumn", com.vladmihalcea.hibernate.type.array.IntArrayType.INSTANCE)
                ;


        List<Object[]> objectCollection = (List<Object[]>) query.getResultList();

the question is why is the following not working and giving the error in hibernate 5.3.7.Final and org.hibernate.dialect.PostgreSQL95Dialect.

o.h.e.j.s.SqlExceptionHelper             : SQL Error: 0, SQLState: 42601
o.h.e.j.s.SqlExceptionHelper             : ERROR: syntax error at or near ":"
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
2
  • 1
    Using Postgres' custom typecast will confuse Hibernate, because it thinks of that as a parameter. You can try cast (array[] as integer[]) or array[]\\:\\:integer[]. Commented Dec 13, 2018 at 22:15
  • @coladict you are completely right. The cast operator works with this constellation i.e. "cast (array[] as integer[])" perfectly. Please put that as an answer i will accept it. Commented Dec 14, 2018 at 13:49

1 Answer 1

2

Hibernate considers things starting with : as parameters, so your query is compiled to:

SELECT  ARRAY[]:?[] AS singleTestColumn

You need to either use an escape sequence (I used this in Hibernate 4.3):

String sql_query = "SELECT  ARRAY[]\\:\\:integer[] AS singleTestColumn";

or the standard SQL cast:

String sql_query = "SELECT  CAST(ARRAY[] AS integer[]) AS singleTestColumn";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.