Saving Files in Derby with Hibernate

Snowflake

I use a byte-array to persist a file in a database with hibernate. After converting file data to a byte-array i map the byte-array to a property of type BINARY:

Entity class:

public class Attachment implements Serializable {
  private byte[] fileData;
  public byte[] getFileData() {
    return fileData;
  }
  public void setFileData(byte[] fileData) {
    this.fileData = fileData;
  }
}


Hibernate mapping:

<hibernate-mapping package="sernet.verinice.hibernate.model">
<class name="AttachmentFile" table="attachment">
  ..
  <property name="fileData" type="binary" >
    <!-- 10 MB = 10485760 B -->
    <column name="fileData" length="10485760"/>
  </property>
  ..
  </class>
</hibernate-mapping>

I used PostgreSQL first and everything works fine. Hibernate maps binary-types in PostgreSQL to column type BYTEA.

After switching to Derby i noticed that hibernate tries to map the byte-array to a VARCHAR(255) which of course is to small for a normal file. You can fix this by extending the build in derby-dialect. In the extended dialect you map the binary type to a BLOB:

public class ByteArrayDerbyDialect extends org.hibernate.dialect.DerbyDialect {
  public ByteArrayDerbyDialect() {
    super();
    // override VARBINARY mapping to varchar($l) from DerbyDialect(DB2Dialect)
    registerColumnType( Types.VARBINARY, "blob($l)" );
  }
}

To use the new dialect you have to set hibernate property hibernate.dialect:

hibernate.dialect=your.package.ByteArrayDerbyDialect

  1. No trackbacks yet.

Schreibe einen Kommentar

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s

%d Bloggern gefällt das: