Is there a way to configure a default typemapping for the UUID type

Viewed 232

I know how to map UUID's to varchar using Hibernate's @Type mapping. However, I wonder if there is a way to tell Hibernate (in a Spring Boot app) to use this @Type("uuid-char") whenever it encounters a UUID in an entity?

1 Answers
  1. You need to override contributeTypes method for your hibernate dialect. See, for example, PostgreSQL82Dialect.

  2. The added in this way type should also override registerUnderJavaType like PostgresUUIDType does it. But UUIDCharType does not do it.

So, you can declare your own type, like below:

import org.hibernate.dialect.Dialect;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.LiteralType;
import org.hibernate.type.StringType;
import org.hibernate.type.descriptor.java.UUIDTypeDescriptor;
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;

public class MyUUIDCharType extends AbstractSingleColumnStandardBasicType<UUID> implements LiteralType<UUID>
{
   public static final MyUUIDCharType INSTANCE = new MyUUIDCharType();

   public MyUUIDCharType() {
      super( VarcharTypeDescriptor.INSTANCE, UUIDTypeDescriptor.INSTANCE );
   }

   @Override
   public String getName() {
      return "my-uuid-char";
   }

   @Override
   protected boolean registerUnderJavaType() {
      // register this type under UUID when it is added to the basic type registry
      return true;
   }

   @Override
   public String objectToSQLString(UUID value, Dialect dialect) throws Exception {
      return StringType.INSTANCE.objectToSQLString( value.toString(), dialect );
   }
}

and then register it:

public class MyPostgreSQLDialect extends PostgreSQL95Dialect
{
   // ...
   
   @Override
   public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry)
   {
      typeContributions.contributeType( MyUUIDCharType.INSTANCE );
   }
}

But if you are going to use UUID as a PK please note that saving UUID as a string can lead to the performance issue, as it explained in this article:

Aside from the 9x cost in size (36 vs. 4 bytes for an int), strings don’t sort as fast as numbers because they rely on collation rules.

Look also at HHH-9577.

Related