Hello community,
we want to use UserTypes to achieve TypeSafe DAOs in our application. This means we want to use Java Pojos as DB Id. Therefore we wrote a Custom IdentifierGenerator providing the Pojos. Now we need a Usertype to make the conversion from the db datatype (here: long) and the Pojo. Unfortunately this does not work which means I cannot insert the long value in the JDBC PreparedStatement.
My Code looks like this:
UserType:
Code:
public class CustomUserType implements UserType {
private static final int[] SQL_TYPES = {Types.LONGVARBINARY};
@Override
public int[] sqlTypes () {
return SQL_TYPES;
}
@Override
public Class returnedClass () {
return JavaPojo.class;
}
@Override
public boolean equals ( Object x, Object y ) throws HibernateException {
if ( x == y ) {
return true;
}
if ( x == null || y == null ) {
return false;
}
return x.equals ( y );
}
@Override
public int hashCode ( Object x ) throws HibernateException {
return x.hashCode ();
}
@Override
public Object nullSafeGet ( ResultSet rs, String[] names, Object owner ) throws HibernateException, SQLException {
long id = rs.getLong ( names[0] );
if ( rs.wasNull () ) {
return null;
}
return new JavaPojo ( id );
}
@Override
public void nullSafeSet ( PreparedStatement st, Object value, int index ) throws HibernateException, SQLException {
if ( value == null ) {
st.setNull ( index, SQL_TYPES[0] );
} else {
JavaPojo javaPojo = (JavaPojo) value;
st.setLong ( index, javaPojo.getId () );
}
}
@Override
public Object deepCopy ( Object value ) throws HibernateException {
return value;
}
@Override
public boolean isMutable () {
return false;
}
@Override
public Serializable disassemble ( Object value ) throws HibernateException {
return (Serializable) value;
}
@Override
public Object assemble ( Serializable cached, Object owner ) throws HibernateException {
return cached;
}
@Override
public Object replace ( Object original, Object target, Object owner ) throws HibernateException {
return original;
}
}
The Mapping:
Code:
<id name="id" column="ID" type="package.CustomUserType" access="field">
<generator class="package.CustomGenerator" />
</id>
The Generator:
Code:
public class CustomGenerator implements IdentifierGenerator
{
@Override
public Serializable generate ( SessionImplementor arg0, Object arg1 ) throws HibernateException {
long idLong = new Long ( new Date ().getTime () + new Random ().nextInt ( 1000 ) );
return new JavaPojo ( idLong );
}
}
When executing this line
Code:
st.setLong ( index, javaPojo.getId () );
will throw an Exception about cannot transform type.
We use Hibernate 3.5.6
Has anybody experience in Usertypes with Long values?
I'm happy for any help
regards