使用spring使用blob存储实体的“最佳”或规范方法是什么?
@Entity
public class Entity {
@Id
private Long id;
@Lob()
private Blob blob;
}
public interface Repository extends CrudRepository<Entity, Long> {
}发布于 2017-11-20 08:11:50
TL;DR
你可以看到在我的github上的示例项目。该项目显示了如何向数据库/从数据库流数据。
问题
所有关于将@Lob映射为byte[]失败(IMO)的建议都是blobs流的主要优势。有了byte[],所有东西都会加载到内存中。也许可以,但如果您使用LargeObject,您可能想要流。
解决方案
映射
@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将会话工厂公开为bean:
@Bean // Need to expose SessionFactory to be able to work with BLOBs
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
return hemf.getSessionFactory();
}创造水珠
@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。
发布于 2016-05-29 11:36:04
自动创建存储库接口,并调用保存方法,传递实体对象。
我有一个类似的设置,效果很好:
@Autowired
Repository repository;
repository.save(entity);
@Entity
@Table(name = "something")
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Lob
@Column
private byte[] data;发布于 2018-05-22 05:39:39
Spring数据不处理BLOB,但弹簧含量处理。具体来说,Spring将内容存储为数据库中的BLOB,并通过注释将该内容与实体关联。
pom.xml
<!-- Java API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-jpa-boot-starter</artifactId>
<version>0.0.11</version>
</dependency>
<!-- REST API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-rest-boot-starter</artifactId>
<version>0.0.11</version>
</dependency>Entity.java
@Entity
public class Entity {
@Id
@GeneratedValue
private long id;
@ContentId
private String contentId;
@ContentLength
private long contentLength = 0L;
// if you have rest endpoints
@MimeType
private String mimeType = "text/plain";DataContentStore.java
@StoreRestResource(path="data")
public interface DataContentStore extends ContentStore<Data, String> {
}与接受的答案相比,这种方法的优点是开发人员不需要担心任何样板代码(可接受答案中的“服务”)。BLOB还公开为Spring提供了一个自然的编程接口。也可以通过REST接口自动导出。但是,除了java配置和存储接口之外,所有这些都不需要代表开发人员进行任何编码。
https://stackoverflow.com/questions/31469136
复制相似问题