Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force Hibernate to return an empty value instead of null?

Tags:

java

hibernate

I'm using Oracle 11GR2 and when the varchar2 field is empty, doing a System.out.println on the empty field will display null on my Eclipse console. How can I have it display the empty string instead?

like image 995
mrjayviper Avatar asked Jan 10 '13 06:01

mrjayviper


People also ask

How hibernate handle null values?

The best way to avoid Hibernate's attempts at setting null values to primitives is to use Wrapper classes (Integer, Long, Double...); and especially, if you need to tack on a column or 2 to an existing table.

Does null count as empty?

A string refers to a character's sequence. Sometimes strings can be empty or NULL. The difference is that NULL is used to refer to nothing. However, an empty string is used to point to a unique string with zero length.

Can primary key be null in hibernate?

No. Primary keys can not be null.

What is nullable true in hibernate?

Hibernate doesn't perform any validation if you annotate an attribute with @Column(nullable = false). This annotation only adds a not null constraint to the database column, if Hibernate creates the database table definition. The database then checks the constraint, when you insert or update a record.


Video Answer


2 Answers

doing the trick in getter is fine but it kind of change the desired behavior of the model.

As quoted in my comment, Oracle has no way to distinguish between empty string and null. If you are sure that all string attribute you are using will never be null, you may create an interceptor in hibernate 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 may refer to Hibernate's document for use of interceptor

like image 94
Adrian Shum Avatar answered Nov 14 '22 22:11

Adrian Shum


your getter method:

public String getVarchar2()
{
    if(this.varchar2==null)
        return "";
    else
        return this.varchar2;
}
like image 43
PC. Avatar answered Nov 14 '22 23:11

PC.