I use next for mapping varchar to boolean (can be null).It work for hibernate 3.x
Code:
package yu.co.snpe.dbtable.model.hibernate.type;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;
/**
* @author snpe
*
*/
public class StringToBooleanUserType implements UserType,ParameterizedType {
// default true value is 'D', default false = null
private String stringTrue = "D";
private String stringFalse = null;
public void setParameterValues(Properties parameters) {
stringTrue = parameters.getProperty("stringTrue");
stringFalse = parameters.getProperty("stringFalse");
}
public int[] sqlTypes() {
return new int[] { Types.VARCHAR };
}
public Class returnedClass() {
return boolean.class;
}
public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
String val = rs.getString(names[0]);
if (null != val && val.equals(stringTrue))
return true;
return false;
}
public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException {
if (((Boolean) value).booleanValue())
st.setString(index, stringTrue);
else if (stringFalse == null)
st.setNull(index, Types.VARCHAR);
else
st.setString(index,stringFalse);
}
public Object deepCopy(Object value) throws HibernateException {
return value;
}
public boolean isMutable() {
return false;
}
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable)value;
}
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (null == x || null == y)
return false;
return x.equals(y);
}
}
and for 0, 1 mapping is :
Code:
<typedef name="ZeroOrOne"
class="yu.co.snpe.dbtable.model.hibernate.type.StringToBooleanUserType">
<param name="stringTrue">1</param>
<param name="stringFalse">0</param>
</typedef>
regards