SQL Zone is brought to you in partnership with:

Jerry is a DZone MVB and is not an employee of DZone and has posted 6 posts at DZone. You can read more from them at their website. View Full User Profile

Annotating Custom Types in Hibernate

03.04.2010
| 34799 views |
  • submit to reddit

Hibernate has a lot of nice features, and it's pretty well documented, but a recent need to add a simple custom type to an existing mapping left me flailing around for documentation on exactly how to do it. I wanted to do it with annotations, not by updating the Hibernate configuration (that approach is well-documented). Here's how it's done.

Two new classes are needed.  You can do it with one (and the Hibernate examples do it that way), but they really have different functions, so I coded them separately.

The first is the class you want to use for the column.  In my case, I needed a Date with no milliseconds, which is a thin wrapper over java.util.Date.  Here's my class:

/**
* Oracle stores dates in DATE columns down to the second; Java stores them to the millisecond.
* This occasionally can confuse Hibernate as to what data are stale. This class slices off
* any milliseconds which might be present in its representation.
*/
public class DateNoMs extends java.util.Date {
private static final long serialVersionUID = 1L;


/** @see java.util.Date() */
public DateNoMs() {
super();
long t = getTime();
setTime(t - t%1000);
}


/** @see java.util.Date(long) */
public DateNoMs(long time) {
super(time - time%1000);
}

/**
* @param value
*/
public DateNoMs(Date value) {
long t = value.getTime();
setTime(t - t%1000);
}


/** @see java.util.Date#setTime(long) */
@Override
public void setTime(long time) {
super.setTime(time - time%1000);
}
}

Straightforward, right?  Now, in my class, I have a field mapping:

    @Column(name = "PAYMENT_DATE")
private DateNoMs m_paymentDate;

Of course, this won't run--Hibernate will gag on the mapping, because it doesn't know how to map a JDBC DATE column to a DateNoMs--as one would expect.  There are two things we need at this point: first, an object which Hibernate can use to transform JDBC DATE into a DateNoMs, and an annotation pointing to that "Factory".  The factory class is produced by implementing (in the simplest case) org.hibernate.usertype.UserType. Documentation in this interface is pretty thin, but there are good examples available in the Hibernate distribution. Here's my implementation.  I'm greatly helped by the fact that my class (DateNoMs) is very close to java.util.Date, and java.sql.Date extends java.util.Date.

/**
* Map "things" (currently Oracle Date columns) to the DateNoMs.
*/
public class DateNoMsType implements UserType {

/** @see org.hibernate.usertype.UserType#assemble(java.io.Serializable, Object) */
public Object assemble(Serializable cached, @SuppressWarnings("unused") Object owner) {
return cached;
}

/** @see org.hibernate.usertype.UserType#deepCopy(Object) */
public Object deepCopy(Object value) {
if (value==null)
return null;

if (! (value instanceof java.util.Date))
throw new UnsupportedOperationException("can't convert "+value.getClass());
return new DateNoMs((java.util.Date)value);
}

/** @see org.hibernate.usertype.UserType#disassemble(Object) */
public Serializable disassemble(Object value) throws HibernateException {
if (! (value instanceof java.util.Date))
throw new UnsupportedOperationException("can't convert "+value.getClass());

return new DateNoMs((java.util.Date)value);
}

/** @see org.hibernate.usertype.UserType#equals(Object, Object) */
public boolean equals(Object x, Object y) throws HibernateException {
return x.equals(y);
}

/** @see org.hibernate.usertype.UserType#hashCode(Object) */
public int hashCode(Object value) throws HibernateException {
return value.hashCode();
}

/** @see org.hibernate.usertype.UserType#isMutable() */
public boolean isMutable() {
return true;
}

/** @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, String[], Object) */
public Object nullSafeGet(ResultSet rs, String[] names, @SuppressWarnings("unused") Object owner)
throws HibernateException, SQLException {
// assume that we only map to one column, so there's only one column name
java.sql.Date value = rs.getDate( names[0] );
if (value==null)
return null;

return new DateNoMs(value.getTime());
}

/** @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement, Object, int) */
public void nullSafeSet(PreparedStatement stmt, Object value, int index)
throws HibernateException, SQLException {
if (value==null) {
stmt.setNull(index, Types.DATE);
return;
}

if (! (value instanceof java.util.Date))
throw new UnsupportedOperationException("can't convert "+value.getClass());

stmt.setDate( index, new java.sql.Date( ((java.util.Date)value).getTime()) );
}

/** @see org.hibernate.usertype.UserType#replace(Object, Object, Object) */
public Object replace(Object original,
@SuppressWarnings("unused") Object target, @SuppressWarnings("unused") Object owner) {
return original;
}

/** @see org.hibernate.usertype.UserType#returnedClass() */
@SuppressWarnings("unchecked")
public Class returnedClass() {
return DateNoMs.class;
}

/** @see org.hibernate.usertype.UserType#sqlTypes() */
public int[] sqlTypes() {
return new int[] {Types.DATE};
}

}

The core of this class is the two methods which get and set values associated with my new type: nullSafeSet and nullSafeGet.  One key thing to note is that nullSafeGet is supplied with a list of all the column names mapped to the custom datatype in the current query.  In my case, there's only one, but in complex cases, you can map multiple columns to one object (there are examples in the Hibernate documentation).

The final piece of the puzzle is the annotation which tells Hibernate to use the new "Type" class to generate objects of your custom type by adding a new @Type annotation to the column:

    @Type(type="com.gorillalogic.type.DateNoMsType")
@Column(name = "PAYMENT_DATE")
private DateNoMs m_paymentDate;

The @Type annotation needs a full path to the class that implements the userType interface; this is the factory for producing the target type of the mapped column.

If you're going to use your new type in a lot of places, you can shorten the @Type annotation by doing a typedef; you can place this in package-info.java in any package you like (I put mine in the same package as the UserType class).  Here's the line for the type defined above:

@TypeDefs(
{
@TypeDef(name = "dateNoMs", typeClass = com.gorillalogic.type.DateNoMsType.class
}) package com.gorillalogic.type;

Now my column annotation can look like this:

    @Type(type="dateNoMsType")
@Column(name = "PAYMENT_DATE")
private DateNoMs m_paymentDate;

 

That should be enough to get you started.

From http://execdesign.blogspot.com

Published at DZone with permission of Jerry Andrews, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Andrew Ball replied on Mon, 2012/11/05 - 9:49am

Thank you so much for the example!

Under what license is the example code?

Thanks again,

Andrew

Asik Umar replied on Tue, 2012/11/27 - 6:42am

 Hi,

Thank you,
I have one issue with this. I created a CustomType similar to above example. insert is working fine, but while updating value is going as null. To nullSafeSet  method also coming as null. Any Idea

Thanks & Regards

Asik

Dominik Radziszowski replied on Fri, 2013/02/22 - 7:06pm

 There is a small error in equals method.

Should be NULL safe

  /** @see org.hibernate.usertype.UserType#equals(Object, Object) */
   public boolean equals(Object x, Object y) throws HibernateException {
     if (x == null && y == null)
       return true;
     if (x == null)
       return false;
     else
       return x.equals(y);
   }


Anyhow I benefit a lot. Thank you!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.