Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve image from blob via Hibernate (not JDBC)

I've found very nice solution of retrieving images from db/blob thanks to How to retrieve and display images from a database in a JSP page?

But this is solution that uses JDBC connection on every image request.

I'm using Spring 3 annotations and Hibernate 3.

I tried to do similar thing by my 'imageService', which is autowired by annotation in ImageServlet class, but I got nullPointerException, which means that may imageService is not set by Dependency Injection.

Is there any way how to solve that? I don't like to make single jdbc connection on image request.

like image 685
Cichy Avatar asked Jan 28 '12 23:01

Cichy


1 Answers

I hope you are storing the image in the table as a BLOB type(If not try to do so, as this is the best practice). Lets assume you have a Person class with the an image of the person stored in the DB. If you want to map this, just add a property in your person POJO that holds the image.

@Column(name="image")
@Blob
private Blob image;

When you display it, convert it to a byte[] and show.

private byte[] toByteArray(Blob fromImageBlob) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
      return toByteArrayImpl(fromImageBlob, baos);
    } catch (Exception e) {
    }
    return null;
  }



private byte[] toByteArrayImpl(Blob fromImageBlob, 
      ByteArrayOutputStream baos) throws SQLException, IOException {
    byte buf[] = new byte[4000];
    int dataSize;
    InputStream is = fromImageBlob.getBinaryStream(); 

    try {
      while((dataSize = is.read(buf)) != -1) {
        baos.write(buf, 0, dataSize);
      }    
    } finally {
      if(is != null) {
        is.close();
      }
    }
    return baos.toByteArray();
  }

You can see the below examples to know more about it.

  1. http://i-proving.com/2006/08/23/blobs-and-hibernate
  2. http://snehaprashant.blogspot.com/2008/08/how-to-store-and-retrieve-blob-object.html
  3. http://viralpatel.net/blogs/2011/01/tutorial-save-get-blob-object-spring-3-mvc-hibernate.html

As you can see there are multiple ways to do this. Choose the one appropriate for you.

like image 81
ManuPK Avatar answered Nov 07 '22 01:11

ManuPK