Categories
Coding

ClassCastExceptions and Hibernate mappings

Hibernate Annotations and binary mappings

I just had an issue where Hibernate was throwing ClassCastExceptions when trying to persist an entity to the database. I tracked the problem down a specific property – a byte[]. I had just switched my entity mappings from a hbm.xml file to an annotations-based approach. The solution was fairly straightforward, as it turned out – just specify the mapping type explicitly as “binary”. It seems that Hibernate may be attempting to map it as a blob type, which doesn’t map transparently to primitive byte arrays (yet – I see there is a PrimitiveByteArrayBlobType in the Hibernate Annotations API). Meanwhile, I just declare the mapping like so:




  @Column
  @Type(type="binary")
  public byte[] getRawData() {
    return rawData;
  }