In this article we will see how Hibernate provides built-in types that map to common database types. We'll also see how Hibernate allows us to implement and use custom types when these built-in types do not satisfy the application's requirements, or when we want to change the default behavior of a built-in type. As you will see, you can easily implement a custom-type class and then use it in the same way as a built-in one.

Hibernate allows transparent persistence, which means the application is absolutely isolated from the underlying database storage format. Three players in the Hibernate scene implement this feature: Hibernate dialect, Hibernate types, and HQL. The Hibernate dialect allows us to use a range of different databases, supporting different, proprietary variants of SQL and column types. In addition, HQL allows us to query persisted objects, regardless of their relational persisted form in the database.

Hibernate types are a representation of databases SQL types, provide an abstraction of the underlying database types, and prevent the application from getting involved with the actual database column types. They allow us to develop the application without worrying about the target database and the column types that the database supports. Instead, we get involved with mapping Java types to Hibernate types. The database dialect, as part of Hibernate, is responsible for transforming Java types to SQL types, based on the target database. This gives us the flexibility to change the database to one that may support different column types or SQL without changing the application code.

Built-in types

Hibernate includes a rich and powerful range of built-in types. These types satisfy most needs of a typical application, providing a bridge between basic Java types and common SQL types. Java types mapped with these types range from basic, simple types, such as long and int, to large and complex types, such as Blob and Clob. The following table categorizes Hibernate built-in types with corresponding Java and SQL types:

Although the SQL types specified in the table above are standard SQL types, your database may support somewhat different SQL types. Refer to your database documentation to find out which types you may use instead of the standard SQL types shown in the table above.

Don't worry about the SQL types that your database supports. The SQL dialect and JDBC driver are always responsible for transforming the Java type values to appropriate SQL type representations.

The type attribute specifies Hibernate types in mapping definitions. This helps Hibernate to create an appropriate SQL statement when the class property is stored, updated, or retrieved from its respective column.

The type attribute may appear in different places in a mapping file. You may use it with the <id>, <property>, <discriminator>, <index>, and <element> elements. Here is a sample mapping file with some type attributes in different locations:

If a property is mapped without the type attribute, Hibernate uses the reflection API to find the actual type of that property and uses the corresponding Hibernate type for it. However, you should specify the type attribute if that property can be mapped with more than one Hibernate type. For example, if a property is of type java.lang.String, and its mapping definition does not include the type attribute, Hibernate will use the reflection API and select the type string for it. This means you need to explicitly define the Hibernate type for a Java String if you want to map the String with a character or text Hibernate type.

Custom types

For most mappings, Hibernate's built-in types are enough. However, in some situations, you may need to define a custom type. These situations generally happen when we want Hibernate to treat basic Java types or persistent classes differently than it normally would. Here are some situations where you may need to define and use a custom type:

Storing a particular Java type in a column with a different SQL type than Hibernate normally uses: For example, you might want to store a java.util.Date object in a column of type VARCHAR, or a String object in a DATE column.

Mapping a value type: Value types, the dependent persistent classes that do not have their own identifiers, can be mapped with custom types. This means you can treat value types similarly to primitive types and map them with the <property> element, instead of <component>.

Splitting up a single property value and storing the result in more than one database column: For example, assume that any phone number is split-up into four components—representing country code, area code, exchange, and line number, stored in four columns of the database. We may take this approach to provide a search facility for countries, areas, exchanges, and line numbers. If the phone numbers are represented as long numbers populated from four columns, we need to define a custom type and tell Hibernate how to assemble the number.

Storing more than one property in a single column: For example, if a papersproperty of a Student class is represented as an object of java.util.List and holds the file paths of all of the papers the student has written. You can define a custom type to persist all of the papers file paths as a semicolon-separated string in a single column.

Using an application-specific class as an identifier for the persistent class: For example, suppose you want to use the application-specific class CustomIdentifier, instead of the int, long, String, and so on, for persistent class identifiers. In this case, you also need to implement an IdentifierGenerator to tell Hibernate how to create new identifier values for non-persisted objects.

In practice, other use cases also need custom types for implementation and use. In all of these situations, you must tell Hibernate how to map a particular Java type to a database representation. You do this by implementing one of the interfaces which Hibernate provides for this purpose. The basic and most commonly used of these interfaces include org.hibernate.usertype.UserType and org.hibernate. usertype.CompositeUserType. Let's look at these in detail, discussing their differences, and how to use them.

UserType

UserType is the most commonly used Hibernate extension type. This interface exposes basic methods for defining a custom type. Here, we introduce a simple case and show how a custom type can provide a convenient mapping definition for it.

Suppose that the history of any school is represented by an individual class, History. Obviously, the History class is a value type, because no other persistent class uses the History class for its own use. This means that all History objects depend on School objects. Moreover, each school has its own history, and history is never shared between schools. Here is the School class:

package com.packtpub.springhibernate.ch07;

import java.io.Serializable;

public class School implements Serializable {

private long id; private History history ; //other fields

//setter and getter methods public long getId() { return id; }

public void setId(long id) { this.id = id; }

public History getHistory() { return history; }

public void setHistory(History history) { this.history = history; }

//other setters and getters}

And this is the History class:

package com.packtpub.springhibernate.ch07;

import java.io.Serializable;import java.util.Date;

public class History implements Serializable { long initialCapacity; Date establishmentDate;

Note that I have intentionally omitted all irrelevant fields of the two classes to keep the example simple.

Our strategy in mapping a value type so far is to use one table for persisting both the persistent class and its associated value types. Based on this strategy, we need to use a SCHOOL table, which stores all of the School and History properties, and then map both School and its History class into that table through the <component> element in the mapping file. The mapping definition for School and its associated History class is as follows:

As an alternative approach, you can map the History class with a custom type. You do this by implementing a custom type, HistoryType, which defines how to map History objects to the target table. Actually, Hibernate does not persist a custom type. Instead, the custom type gives Hibernate information about how to persist a value type in the database. Let's implement a basic custom type by implementing the UserType interface. In the next section of this article, we'll discuss how to map History with an implementation of another Hibernate custom type interface, CompositeUserType.

The following code shows the HistoryType class that implements the UserType interface, providing a custom type for the History class:

The following table provides a short description for the methods in the UserType interface:

Method

Description

public int[] sqlTypes()

This method returns an array of int, telling Hibernate which SQL column types to use for persisting the entity properties. You may use the SQL types defined as constants in the java.sql.Types class directly, or you may call the sqlType() method of Hibernate types defined as constants in the org.hibernate.Hibernate class. For example, in HistoryType, recently discussed, you may alternatively define the types as follows

Note that you should specify the SQL types in the order in which they appear in the subsequent methods.

public Class returnedClass()

This method specifies which Java value type is mapped by this custom type.

public boolean isMutable()

This method specifies whether the value type is mutable. Since immutable objects cannot be updated or deleted by the application, defining the value type as immutable allows Hibernate to do some minor performance optimization.

public Object deepCopy(Object value)

This method creates a copy of the value type if the value type is mutable; otherwise, it returns the current instance. Note that when you create a copy of an object, you should also copy the object associations and collections.

public Serializable disassemble(Object value)

Hibernate may cache any value-type instance in its second-level cache. For this purpose, Hibernate calls this method to convert the value-type instance to the serialized binary form. Return the current instance if the value type implements the java.io.Serializable interface; otherwise, convert it to a Serializable object.

public Object assemble(Serializable cached, Object owner)

Hibernate calls this method when the instance is fetched from the second-level cache and converted back from binary serialized to the object form.

public Object replace(Object original, Object target, Object owner)

Assume that the application maintains an instance of the value type that its associated session has already closed. Such objects are not tracked and managed by Hibernate, so they are called detached. Hibernate lets you merge the detached object with a session-managed persistent object through the session's merge() method. Hibernate calls the replace() method when two instances, detached and session-managed, are merged. The first and second arguments of this method are value-type instances associated with a detached and session-managed persistent object, respectively. The third argument represents the owner object, the persistent object that owns the original value type: School in our case. This method replaces the existing (target) value in the persistent object we are merging with a new (original) value from the detached persistent object we are merging. For immutable objects or null values, return the first argument. For mutable objects, return at least a copy of the first argument through the deepCopy() method.

This method constructs the value-type instance when the instance is retrieved from the database. resultset is the JDBC ResultSet object containing the instance values, names is an array of the column names queried, and owner is the persistent object associated with the value-type instance. Note that you should handle the possibility of null values.

This method is called when the value-type instance is written to a prepared statement to be stored or updated in the database. Handle the possibility of null values. A multi-column type should be written to parameters starting from index.

public boolean equals(Object x, Object y)

This method compares two instances of the value type mapped by this custom type to check whether they are equal.

public int hashCode(Object x)

This method returns a hashcode for the instance, consistent with persistence equality.

In some of the methods shown in the table above, the owner object is passed as an argument to the method. You can use this object if you need the other properties of the value-type instance. For example, you can access a property of the owner if you need it to calculate the value for a value-type property.

Serializing and caching issueIf the value type, in our case History, does not implement the java.io.Serializable interface, then its respective custom type is responsible for properly serializing or deserializing the value type. Otherwise, the value-type instances cannot be cached by the Hibernate second-level cache service.

To use the defined custom type, you need to edit the mapping file as shown below:

Note that you should specify the columns in order, corresponding to the order of types returned by the getTypes() method and the index of the values the nullSafeGet() and nullSafeSet() handle.

So far, all we have done is implemented a custom type in the simplest form. The implemented custom type only transforms the value-type instances to the database columns and vice versa. A custom type may be more complicated than we have seen so far, and can do much more sophisticated things. The advantage of this implemented custom type is obvious: we can define our own strategy for mapping value types. For instance, a property of the value type can be stored in more than one column, or more than one property can be stored in a single column.

The main shortcoming of this approach is that, we have hidden the value-type properties from Hibernate. Therefore, Hibernate does not know anything about the properties inside the value type, or how to query persistent objects based on their associated value types as problem constraints are involved. Let's look at CompositeUserType and how it can solve this problem.

CompositeUserType

Another way to define a custom type is to use the CompositeUserType interface. This type is similar to UserType, but with more methods to expose the internals of your value-type class to Hibernate. CompositeUserType is useful when application query expressions include constraints on value-type properties. If you want to query the persistent objects with constraints on their associated value types, map the associated value types with CompositeUserType. The following code shows the CompositeHistoryType implementation for History:

As you can see, this interface exposes some extra methods not seen in UserType. The following table shows the functionality of these methods:

Method

Description

public String[] getPropertyNames()

This method returns the names of the value type's properties that may appear in the query constraints. In the example shown in the code above, we have used both the initialCapacity and establishmentDate properties, meaning the application can query the persistent objects based on these property values.

public Type[] getPropertyTypes()

This method returns the corresponding types of the properties specified by the getPropertyNames() method. Each returned Type in the array corresponds to a property name with the same index in the array returned by getPropertyNames(). Each type is expressed as an instance of the org.hibernate.type.Type interface, defined as a static member in the org.hibernate.Hibernate class, or a custom type implemented by the developer.

public Object getPropertyValue(Object component, int property)

This method returns a property's value. It takes two arguments. The first argument is the value-type instance that holds the property value we want to fetch. The second argument specifies the index of the property, based on the property name returned by getPropertyNames().

Hibernate uses this method to assign a value to any property of the value-type instance. This method takes three arguments. The first argument refers to the value-type instance, the second specifies the index of the property based on position of the property in the array returned by getPropertyNames(), and the third is the value assigned to the property.

Using this custom type is same as using UserType, except that you need to specify the CompositeHistoryType instead of HistoryType as follows:

As mentioned earlier, this custom type provides an ability to query on properties of the History type. HQL is one approach provided by Hibernate to query the persistent object. For instance, suppose we are interested in schools established before 1980. The following code shows querying these objects with HQL, a Hibernate-specific query language that works with objects:

All we have done in this snippet is created a Query object with an HQL expression indicating all School objects with establishment date before 1980. Note that HistoryCompositeType provides the ability to query the School object with criteria applied to History objects.

The only advantage of CompositeUserType over UserType is that CompositeUserType exposes the value-type properties for Hibernate. Therefore, it lets you query persistent instances based on values of their associated value-type instances.

Summary

In this article, we discussed Hibernate types, which define the mapping of each Java type to an SQL type. It is the responsibility of the Hibernate dialect and the JDBC driver to convert the Java types to the actual target SQL types. This means a Java type may be transformed to different SQL types when different databases are used.

Although Hibernate provides a rich set of data types, called built-in types, some situations require the definition of a new type. One such situation occurs when you want to change Hibernate's default behavior for mapping a Java type to an SQL type. Another situation is when you want to split up a class property to a set of table columns, or merge a set of properties to a table column.

Hibernate provides several interfaces for implementation by custom types. The most commonly used interfaces are org.hibernate.usertype.UserType and org.hibernate.usertype.CompositeUserType. The basic extension point is UserType. It allows us to map a value-type, but hides the value-type properties from Hibernate, so it does not provide the application with the ability to query value types. In contrast, CompositeUserType exposes the value-type properties to Hibernate, and allows Hibernate to query the value-types.