lazy column loading in Grails domain class

2019-05-20 09:59发布

问题:

I have a domain class like this:

class Document {
 String mime;
 String name;
 byte[] content;

 static mapping = {
  content lazy:true;
 }
}

and I'd like to enable lazy loading to the "content" column, because the application does some stuff without the need of access to this column.

But the lazy:true option didn't work... any idea or workaround?

回答1:

What do you mean by the application does some stuff? and what are you trying to establish?

FYI. eager and lazy loading usually has to do with relations, grails by default has lazy loading enabled. e.g."

Class Book{
   static belongsTo = Author
   String Name
   Author author
}

Class Author{
   static hasMany = [books:Book]
   String Name
}

def author = Author.get(author_id)
def authorBooks = author.books //===> collection with lazy association by default

In your code there is no relation. content is a property of Document, hence lazy loading doesn't apply here.

http://grails.org/doc/1.0.x/guide/5.%20Object%20Relational%20Mapping%20(GORM).html



回答2:

There is some discussion here about using Hibernate annotations to lazily load a specific column.

Another possibility is to break your Document object into two pieces. Something like this:

class Document {
    String mime
    String name
    DocumentContent content
}

class DocumentContent {
    static belongsTo = [document:Document]
    byte[] data
}

Since this is a relation, GORM will lazily load the DocumentContent by default.