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> {
}
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> {
}
You can also create
Blob
right fromDataSource
:Autowire your repository interface and call the save method passing your entity object.
I have a similar setup which works pretty well:
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
asbyte[]
defeats (IMO) the main advantage of blobs - streaming. Withbyte[]
everything gets loaded in memory. May be ok but if you go with LargeObject you likely want to stream.Solution
Mapping
Configuration
Expose hibernate SessionFactory and CurrentSession so you can get hold of the LobCreator. In application.properties:
Expose session factory as bean:
Create blob
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 does not handle BLOBs but Spring Content does. Specifically, Spring Content JPA stores content as BLOBs in the database and associates that content with an Entity through annotations.
You can do it with a single statement (4 below) using Hibernate.getLobCreator and passing the session that EntityManager can unwrap to you: