簡體   English   中英

如何將java.sql.Blob寫入JPA實體?

[英]How to write java.sql.Blob to JPA entity?

我有一個帶java.sql.Blob的JPA實體:

@Entity
public class LargeData {

  @Lob
  private java.sql.Blob data;

  //getters/setters
}

如何創建這個實體的實例? 我想用setData()方法設置Blob ,但是如何從JPA獲取Blob java.sql.Blob只是接口,不同的數據庫有不同的實現,所以我假設JPA應該給我正確的實現。 怎么弄?

使用字節數組:

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

如果要使用流,請使用Hibernate.createBlob(..)創建blob

使用文件流。 但是,這似乎有各種復雜性,具體取決於您的數據庫,驅動程序和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);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM