Reputation: 1056
I'm using Spring 4.2.3, Hibernate 5.0.4, JPA 2.1 for purpose of self training in case of ORM. Today I was learning how to store Blob in Oracle 11.2.0.4 DB.
In my application I have Service and Dao layers.
Problem: Why should I create Blob instance using Hibernate.getLobCreator which requires current session? Why it is not possible using [Hibernate.createBlob][3] any more (without accessing current session) ?
In some cases I may need transient domain model with Blob field initialized without need to persist it in DB using Dao.
Is it because of (as written in Blob JavaDoc) :
A Blob object is valid for the duration of the transaction in which is was created.
Sorry for asking silly question but I was unable to find satisfying answer.
[3]: https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Hibernate.html#createBlob(java.io.InputStream, long)
Upvotes: 3
Views: 5255
Reputation: 1056
Ok, I've found some soft of solution of how to initialize Blob without accessing session object.
I used SerialBlob implementation. Below is simple source code sample:
private Blob getBlob(String classpathLocation) {
ClassPathResource imageFile = new ClassPathResource(classpathLocation);
Blob resource = null;
if (imageFile.exists()) {
try {
try (InputStream inputStream = imageFile.getInputStream()) {
resource = new SerialBlob(StreamUtils.copyToByteArray(inputStream));
LOG.warn("Resource loaded from {}", classpathLocation);
}
} catch (Exception e) {
LOG.error(MessageFormat.format("Unable to load resource from {0}", classpathLocation), e);
}
} else {
LOG.warn("Resource do not exist on {}", classpathLocation);
}
return resource;
}
Upvotes: -1
Reputation: 506
Because Hibernate.createBlob has been removed now from hibernate due to some enhancement (i don't remember exact jira issue :). you can find on internet).
So all you can use is new Hibernate.getLobCreator as something like below :
public Blob createBlob(your param) {
return Hibernate.getLobCreator(currentSession()).createBlob();
}
// check different method for createBlob as you want to pass params.
// currentSession is method of HibernateDaoSupport
// pass your session object instead of above
Here Blob is type of java.sql.Blob. Other blob methods for different class are implementing this interface. So you will get proper Blob either you are using oracle or sql server or anything....
So if you are using Hibernate 5.x.x then use like above.
Upvotes: 2