Some of my columns in a PostgreSQL database are arrays too and I'm using a custom user-defined "type" class to convert them between Java and PostgreSQL type.
Example:
Java class:
Code:
public class Test
{
private Long test_id;
private String[] test_arr;
}
Hibernate mapping document:
Code:
<class name="Test" table="test" dynamic-update="true">
<id name="test_id" column="test_id">
<generator class="native"/>
</id>
<property name="test_arr" column="test_arr" type="StringArrayType"/>
</class>
Java class "StringArrayType" (only important methods shown):
Code:
import org.hibernate.usertype.UserType;
public class StringArrayType implements UserType
{
public int[] sqlTypes() {
return new int[] {Types.VARCHAR};
}
public Class returnedClass() {
return String[].class;
}
public Object nullSafeGet(ResultSet arg0, String[] arg1, Object arg2)
throws HibernateException, SQLException
{
final String resultRaw = arg0.getString(arg1[0]);
if (arg0.wasNull())
return null;
else {
Pattern pat = Pattern.compile("[{}]");
Matcher matcher = pat.matcher (resultRaw);
String intermediate = matcher.replaceAll("");
pat = Pattern.compile(",");
return (pat.split (intermediate));
}
}
[...]
}
So, I'm converting the string which is returnd by PostgreSQL and which looks like
Code:
{element1,element1, element3}
by using Java built-in regular expressions string handling into a String array in method nullSafeGet() of a class which implements the Hibernet UserType interface.
There is also a nullSafeSet() method which you must implement if you want to write your Java array back into the database.
I have written similar classes to convert PostgreSQL boolean and floating point arrays. They all seem to work fine.
Look for "custom user type" in the Hibernate documentation for more information.
HTH
- andreas