We help IT Professionals succeed at work.

Can Hibernate persist a string as a number?

BrianMc1958 asked
Dear Experts,

My app processes data from multiple vendors whose formats vary slightly.  99% of the fields are of the same type, but a few vary.  For instance, transaction codes are alpha in some, and numeric in others.  For business reasons, it was decided that our actual databases at customer sites would reflect these differences.

I currently have a home-grown data layer that takes that into account.  This allows my application to treat all such "morphable" fields as Strings internally.  Therefore, I have a single code base that works against a variety of slightly different databases.  When my application asks my data layer to persist a transaction code, for example, it first queries the metadata of the local database, and then persists it either as a string or as an integer.  It reverses the process when I retrieve it.

I'm telling you all this because I'm considering switching to Hibernate.  (Like you folks told me to several years ago.)  I don't know much about Hibernate yet, but that would be the key question.

Can my app tell Hibernate: Take this String, and persist it to some local db field, and if that db field is an integer, first convert the String to an integer?

If so, can you give me an idea of how to go about it, and how much trouble it would be? ( We only have about six such fields we really care about.)

Watch Question

Head of SW Development

You can write your own types in Hibernate. I guess you could implement the logic you are describing in your own custom type. Here is some info on that:


And some examples:


And more:



I'm readng the first link.  Could I ask if this is right?

In addition to standard mappings, Hibernate will let me write my own classes that will encapsulate custom mappings.  Within that class, I can put any logic I want, such as "If the underlying database field is a number, convert it to a String.  Otherwise, just pass String as is."

Is that right?
Dejan PažinHead of SW Development

Yes. And the other way around - you were describing the getter part, naturally you have to implement the setter too. You do that in the nullSafeSet and nullSafeGet methods of UserType interface.

I suggest you give it a try, if this is an important feature for you.


Thanks very much.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.