Grails领域类的父类及save方法实际执行类技术咨询
Grails Domain Classes: Parent Classes/Interfaces and the
save() Method Deep Dive Great question—this gets to the heart of how Grails GORM (Grails Object Relational Mapping) works under the hood. Let's break it down clearly:
1. Parent Classes & Interfaces for Grails Domain Classes
Grails domain classes rely on dynamic runtime enhancements (powered by Groovy's metaprogramming) to add persistence capabilities. Here's what's happening behind the scenes:
- Default Groovy Base: All Groovy classes (including Grails domain classes) implicitly inherit from
groovy.lang.GroovyObject, which enables the metaprogramming magic that makes GORM work. - Core GORM Trait: Every Grails domain class is dynamically enhanced to implement the
grails.gorm.GormEntitytrait. This trait defines all the core persistence methods you use daily—likesave(),delete(), and all the dynamicfindBy*()queries. - Supporting Persistence Traits: Domain classes also get mixins for traits like
grails.gorm.DirtyCheckable(handles tracking changes to entity fields) andgrails.gorm.Persistable(defines basic persistence operations), which work together to power the persistence lifecycle.
2. Where Does the save() Method Actually Live?
When you define a simple domain class like:
class Book { String isbn }
And call new Book(isbn: "1").save(), your raw Book class doesn't have a save() method in its source code. Here's the full flow:
- At application startup, Grails generates a dynamic proxy class for your
Bookdomain. This proxy extends your originalBookclass and implementsGormEntity<Book>. - The
save()method you call comes directly from theGormEntitytrait's default implementation. This method handles:- Checking if the entity is new (for an
INSERT) or modified (for anUPDATE) - Running validation rules (if you haven't disabled them)
- Delegating the actual database operation to Grails'
Datastorelayer.
- Checking if the entity is new (for an
- By default, Grails uses Hibernate as the underlying datastore. The
Datastorewill use Hibernate'sSessionto execute the appropriate SQL statement for your entity.
To see this in action, you can run a quick check in the Grails console:
def book = new Book(isbn: "1") println book.getClass().name // Outputs a generated proxy name like 'Book_$$_jvstc6b_0' println book instanceof grails.gorm.GormEntity // Returns true
内容的提问来源于stack exchange,提问作者Kapil Arora




