How to make Hibernate return an empty value instead of null?

I am using Oracle 11GR2, and when the varchar2 field is empty, null will be displayed in the System.out.println field in the empty field in my Eclipse console. How can I display an empty string?

+6
source share
3 answers

your getter method:

 public String getVarchar2() { if(this.varchar2==null) return ""; else return this.varchar2; } 
+3
source

The getter trick is fine, but it’s like a change in the desired behavior of the model.

As pointed out in my comment, Oracle is not able to distinguish between empty string and null. If you are sure that the whole string attribute that you use will never be null, you can create a sniffer in sleep mode, like this

 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; } } 

You can contact Hibernate to use an interceptor.

+5
source

An interceptor is the way to go if you want to change the behavior for all lines. Oracle internally treats the empty string as null ( '' is null returns true), but this may not be true for other databases. For them, you must override the onFlushDirty and onSave , and also not use null in the database (or always use them if you want):

 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; } } 

You can contact Hibernate to use an interceptor.

+1
source

All Articles