如何使用 ObjectTypeConverter 来管理空值?
How can I use ObjectTypeConverter to manage null values?
我有这个转换器可以将 Boolean.class 字段从实体转换为 Oracle DB 中的 VARCHAR(1):
@ObjectTypeConverter(name = "SNtoBoolConverter",
dataType = java.lang.String.class,
objectType = java.lang.Boolean.class,
conversionValues = {
@ConversionValue(dataValue = "S", objectValue = "true"),
@ConversionValue(dataValue = "N", objectValue = "false"),
}
)
有没有办法将空值转换为字符?
谢谢!
不,您需要使用 custom converter。类似于:
@Converter(name="SNtoBoolConverter",
converterClass=org.myorg.converters.SNtoBoolConverter.class)
Boolean yourProperty;
public class SNtoBoolConverter implements org.eclipse.persistence.mappings.converters.Converter {
public Object convertDataValueToObjectValue(Object dataValue, Session session) {
if ("S".equals(dataValue))
return Boolean.TRUE;
if ("N".equals(dataValue))
return Boolean.FALSE;
return null;
}
public Object convertObjectValueToDataValue(Object value, Session session) {
if (null == value)
return null;
if (value == Boolean.TRUE){
return "S"
} else {
return "N"
}
}
public void initialize(DatabaseMapping mapping, Session session){}
public boolean isMutable() {return false;}
}
我有这个转换器可以将 Boolean.class 字段从实体转换为 Oracle DB 中的 VARCHAR(1):
@ObjectTypeConverter(name = "SNtoBoolConverter",
dataType = java.lang.String.class,
objectType = java.lang.Boolean.class,
conversionValues = {
@ConversionValue(dataValue = "S", objectValue = "true"),
@ConversionValue(dataValue = "N", objectValue = "false"),
}
) 有没有办法将空值转换为字符? 谢谢!
不,您需要使用 custom converter。类似于:
@Converter(name="SNtoBoolConverter",
converterClass=org.myorg.converters.SNtoBoolConverter.class)
Boolean yourProperty;
public class SNtoBoolConverter implements org.eclipse.persistence.mappings.converters.Converter {
public Object convertDataValueToObjectValue(Object dataValue, Session session) {
if ("S".equals(dataValue))
return Boolean.TRUE;
if ("N".equals(dataValue))
return Boolean.FALSE;
return null;
}
public Object convertObjectValueToDataValue(Object value, Session session) {
if (null == value)
return null;
if (value == Boolean.TRUE){
return "S"
} else {
return "N"
}
}
public void initialize(DatabaseMapping mapping, Session session){}
public boolean isMutable() {return false;}
}