Created
August 6, 2013 12:23
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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