How to read bytea image data from PostgreSQL with JPA?

Bhushan picture Bhushan · Feb 19, 2016 · Viewed 32.1k times · Source

I have PostgreSQL database and there is column 'image' with datatype 'bytea'. I cannot modify columns or database configurations. JPA annotated POJO contains followign mapping

@Column(name="image")
private byte[] image;

The returned data is in following format (this is just a sample)

WF5ClN6RlpLZ0hJTUdNQ1FJWmkwcFVGSUdNQ0lDWUE5TUEvanRFeElwK2x0M2tBQUFBQVNVVk9SSzVDWUlJPQo=

When I write this data to file (.jpeg) photo viewer says "this is corrupted file". I also understand that actual image byte data looks different from above sample. I read some blogs which mentioned that PostgreSQL applies hexadecimal conversion to bytea data. How to restore it to original data with or without JPA ?

Database - PostgresSQL Version 9.5.1

Driver

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.4-1205-jdbc41</version>
</dependency>

Answer

josivan picture josivan · Feb 19, 2016

Try to annotate you entity with @Lob

@Lob
@Column(name="image")
private byte[] image;

If you are using hibernate implementation you can add @Type(type="org.hibernate.type.BinaryType") in column too.

@Lob
@Column(name="image")
@Type(type="org.hibernate.type.BinaryType")
private byte[] image;