I'm using Oracle 10g and Hibernate 2.1 (old version, but not allowed to upgrade to fix). I've got a table with a not nullable column named TIN, varchar2(9). This column is used to stage data loaded from flat files and so can store any string of length 9, including 9 spaces (that is: ' ') if the input file had 9 spaces.
What I've noticed is that:
Oracle 10g automatically converts empty strings to NULL. So if you execute:
SELECT NVL('', 'Input string converted to NULL') FROM dual;
the result is 'Input string converted to NULL', not ''. I think this is relevant to the problem.
When Hibernate reads a record where the TIN value is 9 spaces (or any number of spaces) with no other character, it stores the value in memory as ''. Hibernate then seems to trick itself into thinking, so to speak, that the value has changed from 9 spaces to an empty string. Then if the record is written back to the database, Hibernate tries to to write an empty string rather than 9 spaces and Oracle apparently converts this to null and then throws a not-null constraint violation.
For reference, here's the HBM for this column:
<property
name="tin"
type="java.lang.String"
column="TIN"
not-null="true"
length="9">
My question is, how do I instruct Hibernate not to convert values that only contain spaces to empty strings?
Update 1: I just went back and tested strings like ' text ' and found that Hibernate trims these spaces too, making the string 'text' and fooling itself into thinking that the value changed. I must be missing something. This doesn't seem like default behavior.
Update 2: It looks like the hbm2java Ant task that converts the HBM to Java source might be the source of the String trims. Still investigating.
Thanks, Jeff
Edit: Changed question wording to be more precise.