Mapping ARRAY[]::INTEGER[] in hibernate

巧了我就是萌 提交于 2019-12-13 20:27:58

问题


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

回答1:


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";


来源:https://stackoverflow.com/questions/53747733/mapping-arrayinteger-in-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!