You can use the @Lob annotation for your permanent property ( Annotation Lob ):
@Entity public class MyEntity { private byte[] content; ... @Lob public byte[] getContent() { return content; } public void setContent(byte[] newContent) { this.content = newContent; } }
In your code, you can convert the stream to byte [] with the following code:
@Transient public void setContentFromInputStream(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int l = 0; do { l = is.read(buff); if (l > 0) { baos.write(buff, 0, l); } } while (l > 0); is.close(); baos.flush(); baos.close(); content = baos.toByteArray(); }
@Lob annotation can also be used with String, in which case you will get CLOB in DB
You should pay attention to byte size [] to avoid OutOfMemoryError.
To use only streams, you must rely on a specific jdbc provider implementation. For example, if you use Hibernate> = 3.6, you can change their type MyEntity.content to Blob and write:
MyEntity entity = new MyEntity(); Session session = (Session)entityManager.getDelegate(); Blob newContent = session.getLobHelper().createBlob(inputStream, len); entity.setContent(newContent);
Hope this helps you.
source share