通过Hibernate(不是JDBC)从blob中获取图像 [英] Retrieve image from blob via Hibernate (not JDBC)
问题描述
感谢 ,我发现了很好的从 db / blob <如何从JSP页面中的数据库中检索和显示图像?
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?
但是这是在每个图像请求上使用 JDBC连接的解决方案。
But this is solution that uses JDBC connection on every image request.
我正在使用 Spring 3 注释和 Hibernate 3 。
我试图用我的'imageService'来做类似的事情,'imageService'是通过 ImageServlet类中的注释自动装配的,但是我得到了
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.
有没有办法解决这个问题?我不喜欢在图像请求中创建单个jdbc连接。
Is there any way how to solve that? I don't like to make single jdbc connection on image request.
推荐答案
我希望你将图像存储在表中一个BLOB类型(如果不尝试这样做,因为这是最佳实践)。假设你有一个存储在DB中的人的 Person
类和一个图像
。如果你想映射这个,只需在你的人POJO中添加一个属性来保存图像。
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;
当您显示它时,将它转换为 byte [] $
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.
- http://i-proving.com/2006/08/23/blobs-and-hibernate
- http://snehaprashant.blogspot.com/2008/08/how-to-store-and- retrieve-blob-object.html
- http://viralpatel.net/blogs/2011/01/tutorial-save-get-blob-object-spring-3-mvc-hibernate.html
- http://i-proving.com/2006/08/23/blobs-and-hibernate
- http://snehaprashant.blogspot.com/2008/08/how-to-store-and-retrieve-blob-object.html
- 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.
这篇关于通过Hibernate(不是JDBC)从blob中获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!