javahibernatejpacloblob

Lazily loading a clob in hibernate


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?


Solution

  • 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:

    public class MyBlobWrapper {
        @Id
        public Long getId() {
           return id;
        }
        @Lob
        public String getBlob() {
            return blob;
        }
        @OneToOne(fetch=FetchType.LAZY,optional=false) 
        public MyClass getParent() {
            return parent;
        }
    }