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 do it with a single statement (4 below) using Hibernate.getLobCreator and passing the session that EntityManager can unwrap to you:
// 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);
You can see sample project on my github. The project shows how you stream data to/from database.
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;
...
}
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();
}
@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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With