Thursday, November 04, 2021

Changing the Default Type Mapping of Hibernate

By default, Hibernate maps Strings to varchar(255). However, limiting the length of the characters has led to some serious problems. For example, I've seen some systems where the system was truncating important information, and it was only much later on when the system had been in production for a while when the company found out that this was happening. Of course, there was no longer any way to recover that lost data. 

This is why I prefer to use text instead of varchar(255) as the type mapping for Strings. Using varchar(255) offers no performance advantages on modern databases. The only reason to map Strings to varchar(255) is schema portability, but how many times does a company change database brands anyway? And most databases use "text" as the name of their unlimited string type anyway. For those that don't, it's trivial to do a find-replace to change a DDL to the right type name.

To set the default mapping type for Strings, add the following snippet to package-info.java of the package where your have your entities:
@TypeDefs({
        @TypeDef(name="string",defaultForType=java.lang.String.class,
        		typeClass=org.hibernate.type.TextType.class)
})

package com.orangeandbronze.enlistment; // replace with your actual package's name

import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
Hibernate will now generate text columns for String fields.

No comments:

Post a Comment