java class:
Code:
public class Warehouse implements Serializable
{
private UniqueKey id;
mapping:
Code:
<hibernate-mapping>
<class name="ru.xxx.common.security.Warehouse" table="`Warehouse`" batch-size="10">
<cache usage="nonstrict-read-write"/>
<id name="id" column="`WarehouseId`" type="ru.xxx.hibernate.UniqueKeyType" access="field">
<generator class="ru.xxx.hibernate.UniqueKeyGenerator"/>
</id>
<version name="version" column="`Version`" />
<property name="name" column="`WarehouseName`" access="field"/>
</class>
</hibernate-mapping>
Custom type for UniqueKey:
Code:
/**
* Hibernate class for mapping ru.incom.solaris.common.UniqueKey into SQL BIGINT.
*
* @author shl
* @see ru.incom.solaris.common.UniqueKey
* @link http://hibernate.org/50.html
*/
public class UniqueKeyType implements UserType
{
private static final int SQL_TYPES[] = {Types.BIGINT};
public int[] sqlTypes()
{
return SQL_TYPES;
}
public boolean isMutable()
{
return false;
}
public Class returnedClass()
{
return UniqueKey.class;
}
public boolean equals(Object x, Object y)
{
return (x == y) || (x != null && y != null && x.equals(y));
}
public Object deepCopy(Object value)
{
return value;
}
public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException
{
long value = rs.getLong(names[0]);
if (rs.wasNull())
return null;
return UniqueKey.valueOf(new Long(value));
}
public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException
{
if (value == null)
{
st.setNull(index, Types.BIGINT);
}
else
{
long longValue = -1;
// shl: it was _FIXME: sometimes we get value instanceof String, should be instanceof UniqueKey
// shl: is it actual now? I mean such check UniqueKey or String?
if (value instanceof UniqueKey)
{
longValue = ((UniqueKey) value).toLong().longValue();
}
else if (value instanceof String)
{
System.err.println("[WARNING] " + this.getClass() + ".nullSafeSet()" +
" Parameter value: " + value + " operandType: " + value.getClass() +
". Should be: " + UniqueKey.class + " or " + String.class);
longValue = Long.valueOf(value.toString()).longValue();
}
else
{
throw new IllegalArgumentException("Illegal operandType: " + value.getClass() +
" of parameter value: " + value +
". Should be: " + UniqueKey.class + " or " + String.class);
}
st.setLong(index, longValue);
}
}
}
For more examples Search the site for "UserType" key word.