Friday, 22 June 2012

hibernate ClassCastException and Transcient methods

This is an interesting little problem I had.

I have a domain object that has a char(1) column in the database but this is not a boolean. It contains one of two characters 'N' or 'H'.

I mapped this as follows with a handy @Transcient method:

 @Column(name="NHH_HH_IND", nullable=false)
 @Length( max = 1 )
 @NotNull
 @Type(type="java.lang.String")
  public String getHalfHourlyIndicator()
  {
    return mHalfHourlyIndicator;
  }

  public void setHalfHourlyIndicator(String aHalfHourlyIndicator)
  {
    //Integer y = new Integer((String)aHalfHourlyIndicator);
    this.mHalfHourlyIndicator = aHalfHourlyIndicator;
  }
  @Transient
  public boolean isHalfHourlyIndicator()
  {
    if (getHalfHourlyIndicator().equals("H")) {
      return true;
    } else {
      return false;
    }
  }


However when trying to persist this I got a ClassCastException:


java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
at org.hibernate.type.descriptor.java.StringTypeDescriptor.unwrap(StringTypeDescriptor.java:40) at org.hibernate.type.descriptor.sql.VarcharTypeDescriptor$1.doBind(VarcharTypeDescriptor.java:52)

But I had no Boolean objects that were not transcient.

The problem appears to be because the Transcient method has the same body IE 'HalfHourlyIndicator'


Changing this method name to something else solved the problem. This is what I ended up with.

 @Column(name="NHH_HH_IND", nullable=false)
 @Length( max = 1 )
 @NotNull
 @Type(type="java.lang.String")
  public String getHalfHourlyIndicator()
  {
    return mHalfHourlyIndicator;
  }

  public void setHalfHourlyIndicator(String aHalfHourlyIndicator)
  {
    //Integer y = new Integer((String)aHalfHourlyIndicator);
    this.mHalfHourlyIndicator = aHalfHourlyIndicator;
  }
  @Transient
  public boolean isHalfHourlyIndicatorAsBoolean()
  {
    if (getHalfHourlyIndicator().equals("H")) {
      return true;
    } else {
      return false;
    }
  }

1 comment:

Adam Granger said...

We also had this issue, just trying to track down whether it is documented or not, or should raise a bug report against Hibernate as we lost a lot of time on this.