Can't anyone help with this? I want the effect of this which returns a comma separated list of the resource names...
Code:
<property name="requiredResources" type="ResourcesUserType" column="resourceNames" />
...but also with the effect of something like...
Code:
<set name="requiredResources" cascade="save-update" table="RESOURCE">
<key column="RESOURCE_ID" />
<one-to-many class="Resource" />
</set>
The ResourceUserType looks like
Code:
public class ResourcesUserType implements UserType {
@Override
public Object assemble(Serializable arg0, Object arg1)
throws HibernateException {
return arg0;
}
@Override
public Object deepCopy(Object arg0) throws HibernateException {
return arg0;
}
@Override
public Serializable disassemble(Object arg0) throws HibernateException {
return (Serializable)arg0;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
return (x == null) ? (y == null) : x.equals(y);
}
@Override
public int hashCode(Object arg0) throws HibernateException {
return ((Resource)arg0).hashCode();
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
String rResources = (String)Hibernate.STRING.nullSafeGet(rs, names[0]);//rs.getNString("resourceNames");
ArrayList<Resource> returnedResources = new ArrayList<Resource>();
for (String r : rResources.split(",")){
Resource resource = new Resource();
resource.setName(r.trim());
returnedResources.add(resource);
}
return returnedResources.toArray();
}
@SuppressWarnings("unchecked")
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException {
/*DEBUG*/System.out.println("Object Value: "+value);
if (value == null)
throw new IllegalArgumentException( "Received object in nullSafeSet was null - " + returnedClass() );
if (!(value instanceof Set
&& (((Set)value).iterator().next()) instanceof Resource)){
throw new IllegalArgumentException( "Received object in nullSafeSet was " + value.getClass().getName() + " in " + returnedClass() );
}
String resources="";
if (value == null) {
st.setString(index, "");
} else {
//Build the comma separated lists for database
for (Resource r : (Set<Resource>)value){//if this is not a set of resources, the exception would have been thrown already
resources+=r.getName()+",";
}
//remove the additional comma
resources=resources.substring(0,(resources.length()-1));
}
Hibernate.STRING.nullSafeSet(st, resources, index);
}
@Override
public Object replace(Object arg0, Object arg1, Object arg2)
throws HibernateException {
return arg0;
}
@Override
public Class returnedClass() {
return Resource[].class;
}
@Override
public int[] sqlTypes() {
return new int[] {Hibernate.STRING.sqlType()};
}
}