Skip to content

Instantly share code, notes, and snippets.

@vegaasen
Created February 10, 2017 08:00
Show Gist options
  • Save vegaasen/7ffb86fe380f33655ba3c59fc28459e5 to your computer and use it in GitHub Desktop.
Save vegaasen/7ffb86fe380f33655ba3c59fc28459e5 to your computer and use it in GitHub Desktop.
BLOBs with Postgres and Hibernate caused a lot of headace for me

The problem

It seems like mapping a LOB-type from Hibernate is not as easy as you'd think. If you're like me, you'll toss something like the following annotation to a POJO and hoping that all is fine:

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

However, lo and behold - things is not as expected. Hibernate throws all kinds of fancy exceptions - such as:

org.postgresql.util.PSQLException: Bad value for type long : x

So, you'll think that something is wrong with the mapping - and thats right! It seems like Hibernate maps LOBs to OIDs unless others specified. Duh..

The solution

The solution is then to add a Hibernate-specific annotation that specifies the type, such as:

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

This fixes the issue and the bytestream is being feeded to the POJO attribute. Jeay!

Disclaimer

As far as I can understand, this only happens to the following databases:

  • OracleSQL
  • PostgresSQL

We're using the following properties:

Properties props = new Properties();
props.put(Environment.DIALECT, org.hibernate.dialect.PostgreSQL94Dialect.class.getName());
props.put(Environment.FORMAT_SQL, "true");
props.put(Environment.USE_STREAMS_FOR_BINARY, "false");

Enjoy! :-)

@emileastih1
Copy link

Thank you @mark-spooner

@CHINTU1253
Copy link

@lob
@column(name = "ticket", columnDefinition = "BYTEA")
private byte[] ticket;
Hi I'm using this type of annotation I'm storing the image to the database in correct way it was storing in the form binary data and the column type is also bytea. when I'm try to fetch the the data using findall() method it was giving error Could not extract column [2] from JDBC ResultSet [Bad value for type long : \xffd8ffe000104a464946000101..... any suggestions it will really helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment