Retrieve image from blob via Hibernate (not JDBC)

后端 未结 1 1955
耶瑟儿~
耶瑟儿~ 2020-12-09 13:25

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 sol

相关标签:
1条回答
  • 2020-12-09 13:52

    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.

    0 讨论(0)
提交回复
热议问题