如何将java.sql.Blob写入JPA实体?

amo*_*fis 32 java jpa blob

我有一个带java.sql.Blob的JPA实体:

@Entity
public class LargeData {

  @Lob
  private java.sql.Blob data;

  //getters/setters
}
Run Code Online (Sandbox Code Playgroud)

如何创建这个实体的实例?我想BlobsetData()方法设置,但如何Blob从JPA 获取?java.sql.Blob是唯一的接口,不同的数据库有不同的实现,所以我认为JPA应该给我正确的实现.怎么弄?

Boz*_*zho 54

使用字节数组:

@Lob
@Column(length=100000)
private byte[] data;
Run Code Online (Sandbox Code Playgroud)

如果要使用流,请使用创建blob Hibernate.createBlob(..)

  • 接受答案的其他信息.2016年的个人经验证实.http://stackoverflow.com/a/16599953/102658 tl; dr:> length属性用于定义**String**字段的>列长度(对于其他字段,它被忽略)类型**) (5认同)

Phi*_*der 5

使用文件流。但是,这似乎有各种复杂情况,具体取决于您的数据库、驱动程序和 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);
}
Run Code Online (Sandbox Code Playgroud)

通用弹簧/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);
}
Run Code Online (Sandbox Code Playgroud)

和检索:

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);

}
Run Code Online (Sandbox Code Playgroud)