Skip to content

Instantly share code, notes, and snippets.

@Ayrx
Created August 6, 2013 12:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ayrx/6163997 to your computer and use it in GitHub Desktop.
Save Ayrx/6163997 to your computer and use it in GitHub Desktop.
A custom UserType that enables Hibernate to map a Java integer array to a PostgreSQL integer array.
public class IntegerArrayType implements UserType {
protected static final int SQLTYPE = java.sql.Types.ARRAY;
@Override
public Object nullSafeGet(final ResultSet rs, final String[] names, final SessionImplementor sessionImplementor, final Object owner) throws HibernateException, SQLException {
Array array = rs.getArray(names[0]);
Integer[] javaArray = (Integer[]) array.getArray();
return ArrayUtils.toPrimitive(javaArray);
}
@Override
public void nullSafeSet(final PreparedStatement statement, final Object object, final int i, final SessionImplementor sessionImplementor) throws HibernateException, SQLException {
Connection connection = statement.getConnection();
int[] castObject = (int[]) object;
Integer[] integers = ArrayUtils.toObject(castObject);
Array array = connection.createArrayOf("integer", integers);
statement.setArray(i, array);
}
@Override
public Object assemble(final Serializable cached, final Object owner) throws HibernateException {
return cached;
}
@Override
public Object deepCopy(final Object o) throws HibernateException {
return o == null ? null : ((int[]) o).clone();
}
@Override
public Serializable disassemble(final Object o) throws HibernateException {
return (Serializable) o;
}
@Override
public boolean equals(final Object x, final Object y) throws HibernateException {
return x == null ? y == null : x.equals(y);
}
@Override
public int hashCode(final Object o) throws HibernateException {
return o == null ? 0 : o.hashCode();
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Object replace(final Object original, final Object target, final Object owner) throws HibernateException {
return original;
}
@Override
public Class<int[]> returnedClass() {
return int[].class;
}
@Override
public int[] sqlTypes() {
return new int[] { SQLTYPE };
}
}
@mvaneggermond
Copy link

Hi! Thanks for posting this class. The column with the integer array had some null values in my case; I needed to change the 'nullsafeGet' to

  Array array = rs.getArray(names[0]);
        if(array!=null) {

            Integer[] javaArray = (Integer[]) array.getArray();
            return ArrayUtils.toPrimitive(javaArray);

        }
        return ArrayUtils.toPrimitive(new Integer[0]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment