Hibernate and Postgres – a custom UserType to handle arrays

Here is a custom Hibernate UserType that will work to persist Java array types (string[], int[], boolean[], etc..) in a single column. I have seen Oracle implementations, but here is one that uses Java.sql.array and works for Postgres. If you’d like to know more about how this works, Andrew Phillips has written a great explanation of custom Hibernate UserTypes.

Enjoy!

_______________________

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.sql.Array;
import org.hibernate.*;
import org.hibernate.usertype.UserType;
/*
 * Custom UserType implemented to store java array (ie; String[]) types
 */
 public class CustomArrayType implements UserType
 {
 public int[] sqlTypes() {
 return new int[] {Types.VARCHAR};
 }
public Class returnedClass() {
 return String[].class;
 }
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
Array result = null;
 Array array = (Array) resultSet.getArray(names[0]);
 if (!resultSet.wasNull())
 result = array;
 return result;
 }
public void nullSafeSet(PreparedStatement statement, Object value, int index) throws HibernateException, SQLException {
 if (value == null)
 statement.setNull(index, 0);
 else {
 statement.setArray(index, (Array)value);
 }
 }
public Object deepCopy(Object value) throws HibernateException {
 return value;
 }
public boolean isMutable() {
 return false;
 }
@Override
 public Object assemble(Serializable arg0, Object arg1)
 throws HibernateException {
 // TODO Auto-generated method stub
 return null;
 }
@Override
 public Serializable disassemble(Object arg0) throws HibernateException {
 // TODO Auto-generated method stub
 return null;
 }
@Override
 public boolean equals(Object arg0, Object arg1) throws HibernateException {
 // TODO Auto-generated method stub
 return false;
 }
@Override
 public int hashCode(Object arg0) throws HibernateException {
 // TODO Auto-generated method stub
 return 0;
 }
@Override
 public Object replace(Object arg0, Object arg1, Object arg2)
 throws HibernateException {
 // TODO Auto-generated method stub
 return null;
 }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s