jpa blob mysql,spring-data-jpa存储blob

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 blob;

}

public interface Repository extends CrudRepository {

}

解决方案

TL; DR

You can see sample project on my github. The project shows how you stream data to/from database.

Problem

All advices about mapping the @Lob as byte[] defeats (IMO) the main advantage of blobs - streaming. With byte[] everything gets loaded in memory. May be ok but if you go with LargeObject you likely want to stream.

Solution

Mapping

@Entity

public class MyEntity {

@Lob

private Blob data;

...

}

Configuration

Expose hibernate SessionFactory and CurrentSession so you can get hold of the LobCreator. In application.properties:

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext

Expose session factory as bean:

@Bean // Need to expose SessionFactory to be able to work with BLOBs

public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {

return hemf.getSessionFactory();

}

Create 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);

}

}

Also - as pointed out in comments - as long as you work with the @Blob including the stream you get you need to be within transaction. Just mark the working part @Transactional.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值