There's a lot one can find about this googling a bit but I haven't quite found a workable solution to this problem.
Basically what I have is a big CLOB on a particular class that I want to have loaded on demand. The naive way to do this would be:
class MyType {
// ...
@Basic(fetch=FetchType.LAZY)
@Lob
public String getBlob() {
return blob;
}
}
That doesn't work though, apparently due to the fact I'm using oracle drivers, i.e. Lob objects aren't treated as simple handles but are always loaded. Or so I've been led to believe from my forays. There is one solution that uses special instrumentation for lazy property loading, but as the Hibernate docs seem to suggest they're less than interested in making that work correctly, so I'd rather not go that route. Especially with having to run an extra compile pass and all.
So the next solution I had envisioned was separating out this object to another type and defining an association. Unfortunately, while the docs give conflicting information, it's apparent to me that lazy loading doesn't work on OneToOne associations with shared primary key. I'd set one side of the association as ManyToOne, but I'm not quite sure how to do this when there's a shared primary key.
So can anybody suggest the best way to go about this?
Instead of doing equilibristics with hibernate annotations, one may just try converting the field from
String
intoClob
(orBlob
):Worked for me (the field started to load lazily, on Oracle).
Old post, but only one that helped me, thanks to @TadeuszKopec answer.
Looks like it is hard to do lazy loading of blob with JPA. I tried @OneToOne association, but it complicates more than help. I just moved the bytes to another class, with no association with MyClass (parent. Same table, same id):
Just remember to flush parent, before saving the blob:
Now I can load the pdf alone:
I am just beginner with JPA, hope that helps.
Since you appear to be using Hibernate I wonder if your problem is related to the following Hibernate feature:
Using Lazy Properties Fetching
See Bytecode Instrumentation for Hibernate Using Maven.
According to this only PostgreSQL implements Blob as really lazy. So the best solution is to move the blob to another table. Do you have to use a shared primary key? Why don't you do something like this: