如何使用Hibernate选择块中的BLOB并写入文件?

时间:2014-01-27 07:53:07

标签: java hibernate jpa file-io

我需要选择Blob数据并将其写入磁盘上的File。我需要使用我们从Blob获得的二进制流来完成它,但我面对的是OutOfMemoryError,我无法找到解决方法。

实体类:

@Entity
@Table(name = "Table1")
public class AttachmentData implements Serializable
{
    // member variables
    @Column(name = "CONTENT")
    @Lob
    private Blob content;
    // getters, setters
}

实施班级:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("default");
EntityManager em = emf.createEntityManager();
EntityTransaction et = em.getTransaction();
et.begin();
Session session = (Session) em.getDelegate(); // hibernate session
attachmentData = (AttachmentData) session.get(AttachmentData.class, new Long(1000));
InputStream is = attachmentData.getContent().getBinaryStream();
FileOutputStream fos = new FileOutputStream(new File("D:\\MyFile.wmv"));
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte buf[] = new byte[2048];
int len;
while ((len = is.read(buf)) > 0)
{
    bos.write(buf, 0, len);
    bos.flush();
}

使用Hibernate 4.2.1和JPA 1。

1 个答案:

答案 0 :(得分:0)

以下是我如何让它发挥作用:

Session session = (Session) em.getDelegate(); // hibernate session
session.doWork(new Work()
{
    @Override
    public void execute(Connection connection) throws SQLException
    {
        try
        {
            String QUERY_STATEMENT = "SELECT * FROM Table1 WHERE ID= ?";
            PreparedStatement preparedStatement = connection.prepareStatement(QUERY_STATEMENT);
            preparedStatement.setLong(1, new Long(123123));
            ResultSet rs = preparedStatement.executeQuery();

            while (rs.next())
            {
                String fileName = rs.getString("FILE_NAME");
                FileOutputStream outStream = new FileOutputStream(location + fileName);
                InputStream inStream = rs.getBinaryStream("CONTENT");
                try
                {
                    IOUtils.copy(inStream, outStream);
                }
                catch (Exception exc)
                {
                    exc.printStackTrace();
                }
                finally
                {
                    IOUtils.closeQuietly(outStream);
                    IOUtils.closeQuietly(inStream);
                }
            }
        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }
    }
});

问题在于MSSQL驱动程序将整个数据加载到byte []而不是为我提供流。我正在使用Oracle和MSSQL数据库。这为两者提供了通用解决方案。