Hibernate Mapping Types, Code Generation, and Null Values
Posted on November 02, 2004 by Scott Leberknight
One project I'm working is using Hibernate as the persistence framework. We are writing the Hibernate XML mapping files and then generating the POJO model classes. We initially began writing the mapping documents using the Hibernate built-in types like "string", "integer", and "float". A potential gotcha to watch out for is using primitives rather than the wrapper types for numeric fields. The reason is simple - there is no way to set a primitive to a null value since they always assume default values in Java. So if you have a table in your database with a numeric column that allows nulls and a corresponding POJO that uses a primitive to represent the field, when Hibernate tries to hydrate an object from a row in that table it will get really upset because you cannot set a primitive to null!
When generating the POJOs from the Hibernate XML mapping files, we found that some fields in the POJOs were generated as primitives instead of the wrapper types. I am not really sure how exaclty Hibernate decides whether to generate a primitive or a wrapper type, and it doesn't seem consistent as to whether a primitive or wrapper type is generated. Maybe it depends on the database dialect or something like that. In any case, our solution was to set the type attribute of the property elements to the fully-qualified class name such as java.lang.Integer
and java.lang.Long
rather than integer
and long
to force Hibernate to use wrapper types no matter what. For example:
<property name="quantity" column="quantity" type="java.lang.Integer"/>
This ensures that the field in the generated POJO is declared as a java.lang.Integer
and can handle null values. I've read the Hibernate reference documentation, JavaDocs, and Hibernate in Action, and none of these resources seem to mention (that I've found) that you can do this. There is only one example in Hibernate in Action of using the fully-qualified class name as the type for property elements, and that is showing the output of using Middlegen to generate Hibernate mapping files from a database. I would think this would be a common issue and addressed in the books and documentation but apparently not.