Spring-data-jpa storing blob

后端 未结 6 909
梦如初夏
梦如初夏 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 15:15

    I had a little problems to get current session factory like in answers above (got for example errors like: Could not obtain transaction-synchronized Session for current thread) . Finally (in Spring Boot application, currently 2.3.1.RELEASE version, Hibernate 5.4.1) i'm using approach like below and my problems has solved.

    @Component
    public class SomeService {
    
        /**
         * inject entity manager
         */
        @PersistenceContext 
        private EntityManager entityManager;
    
        @Transactional
        public void storeMethod(File file) {
           // ...
           FileInputStream in = new FileInputStream(file);
    
           Session session = entityManager.unwrap(Session.class);
           Blob blob = session.getLobHelper().createBlob(in, file.length());
           // ...
           entity.setData(blob);
           repo.save(entity);
        }
    }
    

提交回复
热议问题