Search code examples
performancehibernategrailsgroovy

How to work around a potential performance issue when using a Grails hasMany relation?


Given the following domain classes:

class Post {
   SortedSet tags
   static hasMany = [tags: Tag]
}

class Tag {
   static belongsTo = Post
   static hasMany = [posts: Post]
}

From my understanding so far, using a hasMany will result in hibernate Set mapping. However, in order to maintain uniqueness/order, Hibernate needs to load the entire set from the database and compare their hashes.

This could lead to a significant performance problem with adding and deleting posts/tags if their sets get large. What is the best way to work around this issue?


Solution

  • There is no order ensured by Hibernate/GORM in the default mapping. Therefore, it doesn't have to load elements from the database in order to do the sorting. You will have your hands on a bunch of ids, but that's that extent of it.

    See 19.5.2: http://www.hibernate.org/hib_docs/reference/en/html/performance-collections.html

    In general, Hibernate/GORM is going to have better performance than you expect. Unless and until you can actually prove a real-world performance issue, trust in the framework and don't worry about it.