Search code examples
javahibernateormdb2hibernate-native-query

Hibernate DB2 Returns First Charector while using NativeQuery


I am facing the following problem while using Hibernate Native Query to fetch data from DB2 CHAR field.

I have a table structure and data as follows.

 CNTRL_4 COLUMN_ID PARAM
 ------- --------- --------------------
       1         1 10                  
       1         2 12                  
       1         3 true                
       2         1 10                  
       2         2 13                  
       2         3 false               
       3         1 10                  
       3         2 16                  
       3         3 true                

CNTRL_4 and COLUMN_ID is number, But PARAM is CHAR(10). If I run the following query manually (From Eclipse SQL Plugin) it fetches the proper result.

SELECT CNTRL_4, COLUMN_ID, VALUE AS PARAM FROM MY_TABLE_NAME 

But if I run the same query with Java Code (Hibernate Native Query) Then I am getiing following Result.

[{CNTRL_4=1, COLUMN_ID=1, PARAM=1}, 
 {CNTRL_4=1, COLUMN_ID=2, PARAM=1}, 
 {CNTRL_4=1, COLUMN_ID=3, PARAM=t}, 
 {CNTRL_4=2, COLUMN_ID=1, PARAM=1}, 
 {CNTRL_4=2, COLUMN_ID=2, PARAM=1}, 
 {CNTRL_4=2, COLUMN_ID=3, PARAM=f}, 
 {CNTRL_4=3, COLUMN_ID=1, PARAM=1}, 
 {CNTRL_4=3, COLUMN_ID=2, PARAM=1}, 
 {CNTRL_4=3, COLUMN_ID=3, PARAM=t}]

Please look at the PARAM data, it is only the first character.

I am using following Java Code

String sql = "SELECT CNTRL_4, COLUMN_ID, VALUE AS PARAM FROM MY_TABLE_NAME";
SQLQuery query = hibernateUtil.getCurrentSession().createSQLQuery(sql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List<Map<String, Object>> data = (List<Map<String, Object>>) query.list();
System.out.println(data);

I also searched on Google and found this blog post, which is same as my problem. As per as I can remember I had solved this problem by typecasting on SQL query. But right now I forget that what I did and not able to solve it now.

Please help.

UPDATE: Problem solved by type casting. Please see my answer.


Solution

  • By type casting we can solve the problem as follows

    SELECT CNTRL_4, COLUMN_ID, RTRIM(CAST (VALUE AS VARCHAR(10))) AS PARAM FROM MY_TABLE_NAME 
    

    Explanation:

    Since VALUE column is defined as CHAR on DB2 and Hibernate is checking the type of the filed while using transformer Criteria.ALIAS_TO_ENTITY_MAP, then it is casting the data to Charecter. So it is returning the first character only.

    But while selecting, if we change the type to VARCHAR then my problem is getting solved.

    Please let me know if there is any disadvantages.