views:

90

answers:

1

I have 2 domain objects with a one-to-many relationship. Just as an example:

Class Author{
  static hasMany = [posts: Post]
}
Class Post{
  Author author
}

In the database the post table has a field called author_id. In my application, I have a bunch of author ids that I want to associate with posts. I can do this by first querying the database for each author, then calling author.addToPosts(post). However, since I already have the ids of the author objects, I should be able to just directly set post.authorId = authorId to make the association (this is all grails will do anyway) and cut down the number of queries requried by half.

In the actual application I'm writing doing this will cut the the amount of queries I need to make by about 70%. This is in a critical bottleneck in the application and I can't afford to have poor SQL performance. I can easily write a sql statement that will do exactly this, but I can't figure out how to get grails to let me directly set the author_id to manually make the association. In rails this sort of functionality is built-in to active-record. Is there a way in grails to do this?

+3  A: 

Configure the 2nd-level cache for Author and get() calls will be retrieved from the cache and not from the database for the most part (instances in the cache will get flushed when edited). Then the net effect will be what you're looking for - the author will be cached and Hibernate can use that to set the Post's foreign key.

Burt Beckwith
Interesting. So in effect I don't need to worry about reducing the number of queries required as a means of optimization with hibernate assuming I have a cache setup (grails doesn't set this up automatically?)? I think I may be starting to see why java people talk so much smack about hibernate. BTW, your UI-Performance plugin is amazing!
David Chanin