我使用的是Oracle 11GR2,当varchar2字段为空时,在Eclipse控制台上对空字段执行System.out.println
将显示null
。如何使其显示空字符串?
public class EmptyStringInterceptor extends EmptyInterceptor {
@Override
public boolean onLoad(Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types) {
for (int i = 0; i < types.length; i++) {
if (StringType.equals(types[i]) && state[i] == null) {
state[i] = "";
}
}
return true;
}
}
您可以参考Hibernate拦截器使用文档。
public String getVarchar2()
{
if(this.varchar2==null)
return "";
else
return this.varchar2;
}
如果您想更改所有字符串的行为,拦截器是一种可行的方法。Oracle在内部将空字符串视为null('' is null
返回true),但其他数据库可能不支持此操作。对于这些数据库,您还应覆盖onFlushDirty
和onSave
方法以避免在数据库中使用null
(或始终使用它们,如果您喜欢):
public class MPSessionInterceptor extends EmptyInterceptor {
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState,
Object[] previousState, String[] propertyNames, Type[] types) {
return convertEmptyStrings(currentState, types);
}
@Override
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
return convertEmptyStrings(state, types);
}
@Override
public boolean onLoad(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
return convertEmptyStrings(state, types);
}
private boolean convertEmptyStrings(Object[] state, Type[] types) {
// convert nulls to empty strings
boolean modified = false;
for (int i=0; i<state.length; i++)
if ((types[i] instanceof StringType) && state[i] == null) {
state[i] = "";
modified = true;
}
return modified;
}
}