Spring-data-jpa 存储 blob

Spring-data-jpa storing blob

什么是 "best" 或使用 spring-data-jpa 使用 blob 存储实体的规范方法?

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

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

自动装配您的存储库接口并调用传递您的实体对象的保存方法。

我有一个类似的设置,效果很好:

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

TL;博士

可以看到sample project on my github。该项目展示了如何流式传输数据 to/from 数据库。

问题

关于将 @Lob 映射为 byte[] 的所有建议都破坏了 (IMO) blob 的主要优势 - 流式处理。使用 byte[] 一切都加载到内存中。可能没问题,但如果你选择 LargeObject,你可能想要直播。

解决方案

映射

@Entity
public class MyEntity {

    @Lob
    private Blob data;

    ...

}

配置

Expose hibernate SessionFactoryCurrentSession 这样你就可以得到 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);
    }
}

另外 - 正如评论中指出的那样 - 只要你使用 @Blob 包括你获得的流,你就需要在交易中。只需标记工作部分@Transactional

Spring 数据不处理 BLOB,但 Spring Content 处理。具体来说,Spring Content JPA 将内容作为 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> {
}

这种方法相对于已接受答案的优势在于开发人员无需担心任何样板代码(已接受答案中的 "service")。 BLOB 也公开为 Spring 资源,提供自然的编程接口。或者可以通过 REST 接口自动导出。但是 none 除了 java 配置和商店界面之外,代表开发人员需要任何编码。

您可以使用 Hibernate.getLobCreator 并通过 EntityManager 可以解包给您的会话通过单个语句(下面的 4)来完成此操作:

// 1. Get entity manager and repository
EntityManager em = .... // get/inject someway the EntityManager
EntityRepository repository = ...// get/inject your Entity repository

// 2. Instantiate your Entity
Entity entity = new Entity();

// 3. Get an input stream (you shall also know its length)
File inFile = new File("/somepath/somefile");
InputStream inStream = new FileInputStream(inFile);

// 4. Now copy to the BLOB
Blob blob =
  Hibernate.getLobCreator(em.unwrap(Session.class))
           .createBlob(inStream, inFile.length());

// 5. And finally save the BLOB
entity.setBlob(blob);
entityRepository.save(f);

您还可以直接从 DataSource 创建 Blob:

@Component
public class LobHelper {

    private final DataSource ds;

    public LobHelper(@Autowired DataSource ds){
         this.ds = ds;
    }

    public Blob createBlob(byte[] content) {
        try (Connection conn = ds.getConnection()) {
            Blob b = conn.createBlob();
            try (OutputStream os = b.setBinaryStream(1);
                 InputStream is = new ByteArrayInputStream(content)) {
                byte[] buffer = new byte[500000];
                int len;
                while ((len = is.read(buffer)) > 0) {
                    os.write(buffer, 0, len);
                }
                return b;
            }
        } catch (Exception e) {
            log.error("Error while creating blob.", e);
        }
        return null;
    }

}

我在获取当前会话工厂时遇到了一些问题,就像上面的答案一样(例如出现错误,如:Could not obtain transaction-synchronized Session for current threadno transaction is in progress)。最后(在 Spring 引导应用程序中,当前为 2.3.1.RELEASE 版本,Hibernate 5.4.1)我正在使用如下方法,我的问题已经解决。

@Component
public class SomeService {

    /**
     * inject entity manager
     */
    @PersistenceContext 
    private EntityManager entityManager;

    @Transactional
    public void storeMethod(File file) {
       // ...
       FileInputStream in = new FileInputStream(file);

       Session session = entityManager.unwrap(Session.class);
       Blob blob = session.getLobHelper().createBlob(in, file.length());
       // ...
       entity.setData(blob);
       repo.save(entity);
    }
}

LobHelper 可能是这样的:

@Service
public class LobHelper {

    @PersistenceContext
    private EntityManager entityManager;

    public Blob createBlob(InputStream content, long size) {
        return ((Session)entityManager).getLobHelper().createBlob(content, size);
    }

    // ...

}