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:
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.
Hi,
nice article. Do you have any Idea how to map the hibernate type within a dialect? I have a problem with a Database that doesn’t allow VARCHAR. So all string-values are filled with whitespaces.
I wrote an own UserType that trims correctly, but now I’d like to set this Type as default for any CHAR column.
Thanks and kind regards
Micha
I have not tried this. But, I would suspect that this should be possible by implementing org.hibernate.type.Type directly or by extending one of the abstract classes in org.hibernate.type package.
Then, use the following method calls in your dialect:
1. Dialect.registerHibernateType(int code, int capacity, String name) to register this type.
2. Dialect.registerColumnType(int code, int capacity, String name) to setup your type mapping.
Good luck..!
Hi Micha,
I encounter the same problem as you, have you tried the solution?
Thanks,
Anne-Lise
Hi,
Nice article (although quite old). I have been trying to implement this solution but it still throws the same error. The scenario is I have a legacy model where they have defined SQL type number(15) as integer Id (Since we use only 6 digits). Now I am trying to switch to hibernate which throws a error
"Expected: class java.lang.Integer, got class java.lang.Long"With thanks and regards
Venkat