gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:34:41 26 4
gpt4 key购买 nike

我需要选择 Blob 数据并将其写入磁盘上的文件。我需要使用从 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。

最佳答案

以下是我如何让它工作:

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 数据库。这为两者提供了通用解决方案。

关于java - 如何使用 Hibernate 选择 block 中的 BLOB 并写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21375527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com