Thursday, April 28, 2011

Calling Postgres function with integer[] input from Hibernate

Situation: Running Hibernate, Postgres. Have function defined in Postgres taking integer[] as input. Have defined in a Hibernate mapping file which calls the function using a variable parameter ":ids". Want to call this , passing in a List. How to do it?

Answer: Create a class named HibernateArrayLongType which extends UserType. Define the two core methods in this class as follows:

public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
Array value = rs.getArray(names[0]);
if (value != null) {
return value.getArray();
}
else
return null;
}

public void nullSafeSet(PreparedStatement statement, Object value, int index)
throws HibernateException, SQLException {

if (value == null) {
statement.setNull(index, Types.ARRAY);
} else {
List list = (List)value;
Long[] array = new Long[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
// the "integer" type name may be specific to Postgres
Array sqlArray = statement.getConnection().createArrayOf("integer", array);
statement.setArray(index, sqlArray);
}

}


In a class which extends HibernateDaoSupport, add this code:

List ids = new ArrayList();
Query query = getSession().getNamedQuery("queryName");
query.setParameter("ids", ids, Hibernate.custom(HibernateArrayLongType.class));
List result = (List)query.list();