Spring-data-jpa storing blob

后端 未结 6 917
梦如初夏
梦如初夏 2021-02-04 14:17

What is \"best\" or canonical way to store entity with blob using spring-data-jpa?

@Entity
public class Entity {
  @Id
  private Long id;
  @Lob()
  private Blob         


        
6条回答
  •  心在旅途
    2021-02-04 14:51

    You can do it with a single statement (4 below) using Hibernate.getLobCreator and passing the session that EntityManager can unwrap to you:

    // 1. Get entity manager and repository
    EntityManager em = .... // get/inject someway the EntityManager
    EntityRepository repository = ...// get/inject your Entity repository
    
    // 2. Instantiate your Entity
    Entity entity = new Entity();
    
    // 3. Get an input stream (you shall also know its length)
    File inFile = new File("/somepath/somefile");
    InputStream inStream = new FileInputStream(inFile);
    
    // 4. Now copy to the BLOB
    Blob blob =
      Hibernate.getLobCreator(em.unwrap(Session.class))
               .createBlob(inStream, inFile.length());
    
    // 5. And finally save the BLOB
    entity.setBlob(blob);
    entityRepository.save(f);
    

提交回复
热议问题