I ran into a problem with Hibernate not converting a char column to a Java String object. In this instance, I was using the createSQLQuery() method on the Session object, like so:
session.createSQLQuery("select char_column from some_table");
I had "char_column" mapped to a String property in my model object (bean). However, at runtime, I was receiving the following nastiness:
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:66)
I also saw this once:
Caused by: java.lang.IllegalArgumentException: java.lang.ClassCastException@95d068
at sun.reflect.GeneratedMethodAccessor59.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:66)
I tried changing the property from a String to an Object and saw that Hibernate was trying to set the char column value as a java.lang.Character object. Not cool - because going that way would result in my 4-character-long database value being truncated to 1 character.
I did some Googling and eventually found this (unaddressed) bug report - "Wrong type detection for sql type char(x) columns".
The simple fix is to cast the column, like so:
session.createSQLQuery("select cast(char_column as varchar) from some_table");
The (supposedly) cleaner fix is to twiddle with a custom dialect, as explained in the above-referenced page by Julien Kronegg. I declined to go this route because I was wary of breaking the application, at large.
Hope this helps.
Leave a comment
6 comments
Thanks for posting this blog! I ran into exactly the same problem when I was creating a quick report with sql without having to map a full entity.
Thank you for the comment, Matthew. I'm glad it helped.
Mike....
AWESOME !! Thanks Michael for saving me the few strands of hair I still have left on my head 😃
thank buddy..its saved lot of time..this sort of posts encourages others to post their own experiences..good job.keep it up
Thnks a ton for this post!!!