There are many real-world scenarios where Hibernate can be introduced on a legacy system that could be using straight JDBC for various reasons.

Also, there could be some pre-existing custom Java types to Database type mapping in the legacy application. Hibernate has it’s default mappings for each database excapsulated in the appropriate SQLDialect classes.

Fortunately, there is a very simple way to customize/override these SQL Types to Database types mappings by extending the SQLDialect class implementation corresponding to the Database in question.

The org.hibernate.dialect.SQLDialect abstract class has these following methods that are provided for overloading the SQL Types to Database types mapping. Also, there is a method to override the standard Database function name mappings:

  • protected void registerColumnType(int code, int capacity, String name)
  • protected void registerColumnType(int code, String name)
  • protected void registerFunction(String name, SQLFunction function)


Here is an example of the usage of one of the above methods to override a mapping of a double (Java SQL type) to a “real” MS SQLServer type.

package com.x.y.common.dao;
import java.sql.Types;
import org.hibernate.dialect.SQLServerDialect;
public class MyMSSQLServerDialect extends SQLServerDialect {
  public MyMSSQLServerDialect() {
    super();
    //Override the default mappings for MS SQLServer
    registerColumnType( Types.DOUBLE, "real" );
  }
}

Also, there is a way to add custom value types in Hibernate by implementing either org.hibernate.UserType or org.hibernate.CompositeUserType.

Technorati Tags: , ,

TOP