如何使用Hibernate将图像流式传输到数据库?

时间:2012-04-20 18:12:41

标签: java image hibernate

非常简单的问题,网上几乎没有答案。我使用byte []作为我的对象。目前我正在将整个图像读入内存然后编写它。非常简单。

    @Column(name = "FILE_DATA")
private byte[] fileData;

我想将其传入。所以我想我需要使用inputStream,但是hibernate不喜欢它。

如何设置?

编辑:

我尝试了这个但是得到了-314 db2错误:

Blob b = null;
        try {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.com", 80));
            URL urls = new URL(url);
            URLConnection conn = urls.openConnection(proxy);
            b = new BlobImpl(conn.getInputStream(), conn.getContentLength());
        } catch (Exception e) {
            e.printStackTrace();
        }

        att.setFileData(b);
        this.theDao.save(att);

3 个答案:

答案 0 :(得分:2)

您可以使用Blob数据类型从数据库中插入和提取图像。它还将为您提供二进制输入流的选项。只需使用db字段作为blob并创建blob ojbect而不是byte array。

b.getBinaryStream()

您也可以从bytes[]

创建Blob
Hibernate.createBlob(bytes);

最简单的解决方案保存在硬盘上并将图像信息保存在数据库中。

答案 1 :(得分:0)

可能的解决方案之一是在数据库中保留文件名(URL)并从磁盘(网络资源)流式传输数据并对其进行流式传输。

我更喜欢这种方法用于网络 - 当你只返回一个URL并由浏览器和Apache / Nginx处理时(所以你根本不用担心流媒体)。

答案 2 :(得分:-1)

我不确定我明白你的意思是“hibernate不喜欢那个”?

这是多么简单的定义。

@Entity Photo {
    @Id @GeneratedValue
    private Long id = null;

    private String filename = null;

    @Lob
    private byte[] bytes = null;
    }

然后将数据加载到对象中......

String filename = // Where ever this comes from...
File file = new File(filename);
InputStream is = new FileInputStream(file);

Photo photo = new Photo();
photo.setFilename(filename);

// Create and fill the byte array from the file.
byte[] bytes = new byte[(int) file.length()];
is.read(bytes);
photo.setBytes(bytes);

然后告诉Hibernate将其保存在数据库中。

session.saveOrUpdate(photo);