TL;博士
你可以看到sample project on my github。该项目展示了您如何将数据流式传输到/从数据库中。
问题
关于将@Lob 映射为byte[] 的所有建议都击败了(IMO)blob 的主要优势 - 流式传输。使用byte[],所有内容都会加载到内存中。可能没问题,但如果您选择 LargeObject,您可能想要直播。
解决方案
映射
@Entity
public class MyEntity {
@Lob
private Blob data;
...
}
配置
公开休眠 SessionFactory 和 CurrentSession 以便您可以获取LobCreator。在application.properties中:
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
将会话工厂公开为 bean:
@Bean // Need to expose SessionFactory to be able to work with BLOBs
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
return hemf.getSessionFactory();
}
创建 blob
@Service
public class LobHelper {
private final SessionFactory sessionFactory;
@Autowired
public LobHelper(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Blob createBlob(InputStream content, long size) {
return sessionFactory.getCurrentSession().getLobHelper().createBlob(content, size);
}
public Clob createClob(InputStream content, long size, Charset charset) {
return sessionFactory.getCurrentSession().getLobHelper().createClob(new InputStreamReader(content, charset), size);
}
}
另外 - 正如 cmets 中所指出的 - 只要您使用 @Blob 包括您获得的流,您就需要在事务中。只需标记工作部分@Transactional。