gpt4 book ai didi

blob - Spring-data-jpa 存储 blob

转载 作者:行者123 更新时间:2023-12-04 09:59:15 24 4
gpt4 key购买 nike

使用 spring-data-jpa 使用 blob 存储实体的“最佳”或规范方式是什么?

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

public interface Repository extends CrudRepository<Entity, Long> {
}

最佳答案

TL; DR

你可以看到sample project on my github .该项目展示了如何将数据传入/传出数据库。

问题

关于映射 @Lob 的所有建议如 byte[]击败 (IMO) blob 的主要优势 - 流媒体。与 byte[]一切都被加载到内存中。可能没问题,但如果你去 L 阿尔格 Ø 您可能想要流式传输的对象。

解决方案

映射

@Entity
public class MyEntity {

@Lob
private Blob data;

...

}

配置

公开 hibernate SessionFactory 和 CurrentSession 以便您可以获取 LobCreator .在 application.properties 中:
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext

将 session 工厂公开为 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);
}
}

此外 - 正如评论中所指出的 - 只要您使用 @Blob包括您获得的流,您需要在事务中。只需标记工作部分 @Transactional .

关于blob - Spring-data-jpa 存储 blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31469136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com