spring-data-jpa存储blob [英] Spring-data-jpa storing blob

查看:744
本文介绍了spring-data-jpa存储blob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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<Entity,  Long> {
}

推荐答案

TL; DR

您可以在我的github上看到示例项目.该项目说明了如何在数据库之间流传输数据.

TL; DR

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

有关将@Lob映射为byte[]的所有建议都会击败(IMO)Blob的主要优势-流式传输.使用byte[],所有内容都会加载到内存中.可能还可以,但是如果您使用 L arge O 对象,则可能需要流式传输.

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.

@Entity
public class MyEntity {

    @Lob
    private Blob data;

    ...

}

配置

暴露休眠 SessionFactory CurrentSession ,这样您就可以掌握

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

将会话工厂公开为bean:

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();
}

创建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.

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.

这篇关于spring-data-jpa存储blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆