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

时间:2011-02-17 16:19:24

标签: java jpa blob

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

@Entity
public class LargeData {

  @Lob
  private java.sql.Blob data;

  //getters/setters
}

如何创建此实体的实例?我想用Blob方法设置setData(),但是如何从JPA获取Blobjava.sql.Blob只是接口,不同的数据库有不同的实现,所以我认为JPA应该给我正确的实现。如何获得它?

2 个答案:

答案 0 :(得分:52)

使用字节数组:

@Lob
@Column(length=100000)
private byte[] data;

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

创建blob

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

}