This is what we did - almost the same
type="com.lsb.uk.mqs.dao.hibernate.PrimitiveIntType"
The PrimitiveIntType has quite a bit of code in it though. I can't help thinking that Hibernate must provide implementations for all primitive types already though.
Surely this must be a common requirement for people (especially those upgrading existing systems)
Here's the code though
package com.lsb.uk.mqs.dao.hibernate;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
Code:
public class PrimitiveIntType implements UserType {
private Integer defaultValue = new Integer(0);
public int[] sqlTypes() {
return new int[] { Types.INTEGER };
}
public Object assemble(Serializable arg0, Object arg1) throws HibernateException {
return arg0;
}
public Object deepCopy(Object arg0) throws HibernateException {
return new Integer(((Integer) arg0).intValue());
}
public Serializable disassemble(Object arg0) throws HibernateException {
return (Serializable) arg0;
}
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);
}
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
public boolean isMutable() {
return false;
}
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
Number result = (Number) rs.getObject(names[0]);
return result == null ? defaultValue : new Integer(result.intValue());
}
public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
if (value == null || defaultValue.equals(value)) {
LogFactory.getLog(getClass()).trace("binding null to parameter: " + index);
st.setNull(index, Types.INTEGER);
} else {
LogFactory.getLog(getClass()).trace("binding " + value + " to parameter: " + index);
st.setInt(index, ((Integer) value).intValue());
}
}
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
public Class returnedClass() {
return int.class;
}
}