Just seeking clarification on one of the finer points of ORM (Hibernate specifically).
I have a domain entity class named 'Vessel' to represent ships. Ships, just like automobiles, have a registration plate type unique identifier called the 'IMO' (usually painted on the stern). Therefore, my Vessel class includes the following field declaration.
It is not a required field, because sometimes the user doesn't yet know the IMO when creating a new vessel. But if the IMO is entered, then it must be unique.
The problem is that when this field is left blank, an IMO of '0' is recorded. Then next time a vessel is created without an IMO, the database (entirely expectedly) protests that a vessel with imo=0 already exists - it is not unique.
I was about to change the IMO field type from int to Integer, but just thought I'd check that this is the correct approach. As perhaps this problem may be solved with an annotation that prevents int from defaulting to zero, which is normal for this primitive variable type.
Also, should I switch to Integer, does Hibernate need to modify the database table column type?
Since the column can be null then it would need to be Integer, a change which only involves the Java side as the column type will be the same on the server.
However, Ron is quite correct in that the IMO is not really a number.
Indeed, by representing it as a String you can ensure it is 7 digits long and, should the number start with a 0, the formatting won't be an issue. If the column is an Integer then '0123456' would end up in the database as '123456' which would involve some work to get it to display correctly, whereas if it were a String then you wouldn't need to worry about that.
But just to answer the literal question. No, converting the Entity class from using int to Integer has no effect on the database schema and (especially since auto-boxing was added to Java) relatively little effect on application code.
And since you can annotate an Integer as @NotNull, this would indeed be effective.
Although I would consider Ron's advice on the true type of this particular item.
"privilege" comes from the Latin words for "private" and "law" (legal) and dates to feudal times. To "claim privilege" meant that you were above the laws that applied to the common people.
posted 1 year ago
Thank you Ron, Dave and Tim,
I took your advice and changed the int field to String rather than Integer. I was probably originally a little too swayed by performance considerations, particularly given the 'imo' column is likely to be indexed. Still, vessel imo and mmsi numbers are not numbers in the true sense of the word, rather labels that just happen to comprise numerical characters. So your advice to use String/varchar makes good sense.