How to Use Customized Type in Object Relational Mapping
When defining class model for your persistent layer, a class is defined as part of the static data model instead of controller or user interface items. And the class is directly mapped to table(s) in your database. As the class is mapped to tables, its attributes is also mapped to columns in table. In order to make the mapping work, you have to model attributes with primitive types like integer, boolean, String, etc. You cannot model the attribute as any other types which are not compatible with database.
To overcome this, you can make use of ORM User Type to define customized datatype for attributes, and persistent its value into database. This article will teach you how to use ORM User Type.
This example simulates how customized type can be used in VP generated ORM layer source code. Assume you have the following model
The MyString type is a wrapper of String which having customized toString method. And the MyEnum is a customized enumerated type. We map MyString to varchar(255) and MyEnum to varchar(1) in database.
Both MyString and MyEnum having <<ORM User Type>> stereotype. This stereotype indicates types used in CustomTable are user type instead of primitive types.
When generate code, VP will generate 2 extra classes, MyStringUserType and MyEnumUserType which implements org.hibernate.usertype.UserType. The MyStringUserType and MyEnumUserType are the linkage between persistent datatype and your custom datatype. Only the class structure for MyStringUserType and MyEnumUserType will be generated and no detail implementation included (since it is up to your decision on how it should behave).
In the mapping file, it will showing the column is map to MyStringUserType and MyEnumUserType.
The MyStringUserType and MyEnumUserType mainly handle how the data being load and save. You must implement the following methods in order to make it work:
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException
To retrieve an instance of the mapped class from JDBC resultset. Note that you need to handle null value situation in your implementation.
public void nullSafeSet(PreparedStatement statement, Object value, int index) throws HibernateException, SQLException
To write an instance of the mapped class to prepared statement. Note that you need to handle null value situation in your implementation.
public Class returnedClass()
Return the name of the object class it should be. For MyEnum, it should return MyEnum.class. And for MyString, it should return MyString.class
public int[] sqlTypes()
To return the actual datatype of the value it stored. Both of them should be VARCHAR type.
By implementing MyStringUserType and MyEnumUserType, you will able to save and load data through your custom types.
“We map MyString to varchar(255) and MyEnum to varchar(1) in data base”. How do you do those mappinps?