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>
The returned Data looks as if it is base64 encoded. You have to decode it back to binary data before writing to file.
For further information to decode look here
I am adding complete code which may be useful for others (skipping try/catch),
Try to annotate you entity with
@Lob
If you are using hibernate implementation you can add
@Type(type="org.hibernate.type.BinaryType")
in column too.insert an image, you would use:
Retrieving the image from the Large Object:
ImageEntity
ImageRepository
Test
It works against Postgres 9.5.0-1 with 9.4.1207.jre7 jdbc driver.