Saving Files in Derby with Hibernate
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
No trackbacks yet.