简体   繁体   中英

Grails GORM Domain class relationship

Grails 1.1.1 Goovy 1.5.7

In a relationship such this:

Author 1 -- n Book n -- 1 Publisher

Defined in Grails:

class Author {        
  String firstName
  String lastName

  static hasMany = [books: Book]       

  static constraints = {
      books(nullable: true)
  }
}

class Book {        
  String title
  Author author
  Publisher publisher

  static constraints = {
    author(nullable: true)
    publisher(nullable: true)
  }
}

class Publisher {

  String name

  static hasMany = [books: Book]

  static constraints = {
      books(nullable: true)
  }
}

I want to load a Book with the values of Publisher and Author. When i get a Book with the query:

def book2 = Book.findAllByAuthor(author)

I get the response with the autor assosiated but the publisher only have the id and name class in the other query:

def book3 = Book.findAllByPublisher(publisher)

I retrieve me the inverse result,i have the book with the publisher data but the author only have the id and the class name.

Where is the error in the defined model ? o there is an error in the way to do the queries ?

Edit:

I need the way to retrieve the values only with the query like this:

def book2 = Book.findAllByAuthor(author, [fetch:[publisher:'eager']])

In this one I can manage the value of publisher.

Question: If publisher had a hasmany or Domain related, getting the book I'm able to read the attributes?

Thanks. Thanks.

Lazy fetching is used by default with gorm associations. If you want to enable eager fetching, you can modify the ORM DSL by adding the following mappings block to your Author domain class:

static mapping = {
    books lazy:false
}

or you could change the fetch mode in the domain object by adding following code after your books relationship is defined.

static fetchMode = [books:"eager"]

Doing the same to your Publisher domain object should allow you to accomplish what you want. You do want to be careful of the consequence that you may load more data than you intend to.

Shouldn't the get() method return what you are looking for? Example: def book2 = Book.get(author)

You'd better use Criteria and explicitly define which relations should be loaded eagerly. Just mention relation in the query.

Example:

def c = Teacher.createCriteria()

List<Teacher> results = c.list {
            subjects {
                attendees {}
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM