这是我对特定列的Hibernate映射:
< property name =“maxRating”not-null =“false”column =“max_rating”/>
在数据库(Postgres)中,列是max_rating双精度,即它在表中可以为空.要映射的Java类具有成员私有浮点数maxRating.
在不更改表定义或类的情况下,有没有办法让Hibernate将此列中的NULL值映射到实例中的Float.NaN?
最佳答案
您应该能够创建用户类型:
原文链接:https://www.f2er.com/java/437897.htmlpackage my.pkg.type;
public class NullNanFloatType implements UserType {
public int[] sqlTypes() {
return new int[]{Types.FLOAT};
}
public Class returnedClass() {
return Float.class;
}
public boolean equals(Object x,Object y) throws HibernateException {
return ( x == y ) || ( x != null && x.equals( y ) );
}
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
public Object nullSafeGet(ResultSet rs,String[] names,Object owner) throws HibernateException,sqlException {
float value = rs.getFloat(names[0]);
if (rs.wasNull()) {
value = Float.NaN;
}
return new Float(value);
}
public void nullSafeSet(PreparedStatement ps,Object value,int index) throws HibernateException,sqlException {
if (value == null || Float.isNaN(((Float)value).floatValue())) {
ps.setNull(index,Types.FLOAT);
} else {
ps.setFloat(index,((Float)value).floatValue());
}
}
public Object deepCopy(Object value) throws HibernateException {
//returning value should be OK since floats are immutable
return value;
}
public boolean isMutable() {
return false;
}
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
public Object assemble(Serializable cached,Object owner) throws HibernateException {
return cached;
}
public Object replace(Object original,Object target,Object owner) throws HibernateException {
return original;
}
}
然后你应该能够将属性映射设置为