Hibernate version: 3
Mapping documents:
<property name="valueAndEntity" type="ValueAndEntityUserType">
<column name="value"/>
<column name="entity" />
</property>
Name and version of the database you are using:
MySQL 5 for Win NT
In the API for CompositeUserType:
Quote:
A CompositeUserType may be used in almost every way that a component may be used. It may even contain many-to-one associations.
For my ValueAndEntityUserType, I want the second column to be a many-to-one association - so a foreign key to the "Entity" table. However, when I use SchemaExport, these foreign keys are not created.
Here's the user type:
Code:
public class ValueAndEntityUserType implements CompositeUserType {
private static final int VALUE = 0;
private static final int ENTITY = 1;
private static final String[] NAMES = { "value", "entity" };
private static final Type[] TYPES = { Hibernate.INTEGER,
Hibernate.entity(Entity.class) };
public String[] getPropertyNames() {
return NAMES;
}
public Type[] getPropertyTypes() {
return TYPES;
}
public Object getPropertyValue(Object component, int property)
throws HibernateException {
ValueAndEntity cd = (ValueAndEntity) component;
switch (property) {
case VALUE:
return new Integer(cd.getValue());
case ENTITY:
return cd.getEntity();
}
throw new IllegalArgumentException("Unknown property index: "
+ property);
}
public Object nullSafeGet(ResultSet rs, String[] names,
SessionImplementor session, Object owner)
throws HibernateException, SQLException {
ValueAndEntity ret = new ValueAndEntity();
ret.setValue(rs.getInt(names[0]));
ret.setEntity((Entity) session.get(
Entity.class, new Long(rs.getLong(names[1]))));
return ret;
}
public void nullSafeSet(PreparedStatement st, Object value, int index,
SessionImplementor session) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.INTEGER);
st.setNull(index + 1, Types.BIGINT);
} else {
ValueandEntity cd = (ValueandEntity) value;
st.setInt(index, cd.getValue());
st.setLong(index + 1, cd.getEntity().getId());
}
}
public Class returnedClass() {
return ValueAndEntity.class;
}
public void setPropertyValue(Object component, int property, Object value)
throws HibernateException {
ValueAndEntity cd = (ValueAndEntity) component;
switch (property) {
case VALUE:
cd.setValue(((Integer) value).intValue());
break;
case ENTITY:
cd.setEntity((Entity) value);
break;
default:
throw new IllegalArgumentException("Unknown property index: "
+ property);
}
}
I thought that since
Code:
getPropertyTypes()
returns
Code:
{ Hibernate.INTEGER, Hibernate.entity(Entity.class) }
that the second column would be a foreign key to the Entity table.
So my questions are: is it possible to have SchemaExport create a foreign key for a column in a CompositeUserType and, if so, what am I doing wrong?? Also, is it appropriate that in
Code:
nullSafeSet
I use
Code:
ret.setEntity((Entity) session.get(Entity.class, new Long(rs.getLong(names[1]))));
?
Thanks in advance,
Luke