Search code examples
javahibernatedb2

Hibernate Query: Casting varchar to (var)binary results in "Unknown column name"


I am trying to read a varchar from an exisiting DB2 table using Hibernate. For some reason, I need the result as an untransformed byte array (e.g. no automatic encoding correction). My first two attempts were to use casting within the session.createNativeQuery

  1. select VARBINARY(MESSAGE_STR) from MyTable where ...;
  2. select cast(MESSAGE_STR as binary) from MyTable where ...;

Both resulting in the same, strange Hibernate Error Unknown column name MESSAGE_STR. ERRORCODE=-4460, SQLSTATE=null.

When I remove the cast in the query and change entity attribute from byte[] to String, the column name is correct. So there is no simple spelling error. Hibernate Core core version is 5.3.7. I would appreciate any comments / thoughts / help here.

Background: The varchar is written into the table by legacy code which can not be changed. It contains real text (in different encodings) as well as binary data (e.g. int value encoded in four bytes). Therefore I need to retreive the (bitwise) exact bytes before I can parse the data.


Solution

  • As suggested by mustaccio, the solution was to use

    select VARBINARY(MESSAGE_STR) as MESSAGE_STR from MyTable where ...

    or elsehow Hibernate would not be able to identify the correct column. Thank you so much!