我有一个带有java.sql.Blob的JPA实体:
@Entity
public class LargeData {
@Lob
private java.sql.Blob data;
//getters/setters
}
如何创建此实体的实例?我想用Blob
方法设置setData()
,但是如何从JPA获取Blob
? java.sql.Blob
只是接口,不同的数据库有不同的实现,所以我认为JPA应该给我正确的实现。如何获得它?
答案 0 :(得分:52)
答案 1 :(得分:4)
使用文件流。 但是,这似乎有各种复杂性,具体取决于您的数据库,驱动程序和JPA实现。 我构建了一个通用的解决方案,这个解决方案速度很慢,并且在使用大型文件时失败了,然后找到了一个适用于Oracle 11.2.0.4的特定于Hibernate的解决方案
我使用的是Spring Data / JPA,但问题似乎是围绕Hibernate,而不是Spring。
休眠:
private void testLoadFile() throws SQLException, IOException {
File f = new File("//C:/tmp/6mb_file.wmv");
BufferedInputStream fstream = new BufferedInputStream(new FileInputStream(f));
Session session = entityManager.unwrap(Session.class);
Blob blob = Hibernate.getLobCreator(session).createBlob(fstream, f.length());
FileBLOBEntity file = new FileBLOBEntity();
file.setName("//C:/tmp/6mb_file.wmv");
file.setTheData(blob);
blobRepository.saveAndFlush(file);
}
Generic Spring / JPA:
private void testLoadFile() throws SQLException, IOException {
File f = new File("//C:/tmp/6mb_file.wmv");
BufferedInputStream fstream = new BufferedInputStream(new FileInputStream(f));
Blob blob = connection.getConnection().createBlob();
BufferedOutputStream bstream = new BufferedOutputStream(blob.setBinaryStream(1));
// stream copy runs a high-speed upload across the network
StreamUtils.copy(fstream, bstream);
FileBLOBEntity file = new FileBLOBEntity();
file.setName("//C:/tmp/6mb_file.wmv");
file.setTheData(blob);
// save runs a low-speed download across the network. this is where
// Spring does the SQL insert. For a large file, I get an OutOfMemory exception here.
blobRepository.saveAndFlush(file);
}
和检索:
public void unloadFile() throws SQLException, IOException {
File f = new File("//C:/tmp/6mb_file.wmv" + "_fromDb");
FileOutputStream fstream = new FileOutputStream(f);
FileBLOBEntity file = blobRepository.findByName("//C:/tmp/6mb_file.wmv");
Blob data = file.getTheData();
InputStream bstream = data.getBinaryStream();
StreamUtils.copy(bstream, fstream);
}