Grails:从src/groovy类访问域类的最佳方法是什么?

Ben*_*Ben 7 grails grails-orm

Grails 常见问题解答说:

问:如何从src/groovy中的源访问域类?

有时,您正在开发一些生活在src/groovy中的实用程序类,您打算在服务和其他工件中使用它们.但是,由于这些类是由Grails预编译的,因此无法实例化它们并编写类似Book.findByTitle("Groovy in> Action")的内容.但幸运的是,有一种解决方法,因为它可以这样做:

import org.codehaus.groovy.grails.commons.ApplicationHolder

// ...

def book = ApplicationHolder.application.getClassForName("library.Book").findByTitle("Groovy in Action")

应用程序必须在动态Gorm方法正常运行之前完成自举.

但是,似乎我可以直接导入域对象并在我的src/groovy类中使用GORM方法而没有任何问题,例如:

Book.findByTitle("Groovy in Action")
Run Code Online (Sandbox Code Playgroud)

由于不推荐使用ApplicationHolder,这个建议必须过时,但是仍然有理由避免直接从src/groovy使用域类吗?

dma*_*tro 6

你是对的,指的是过时的信息.您可以在其中定义的类中使用域类src/groovy.

唯一的开销是你必须transactions手动处理.相反,默认情况下services在内部grails-app/services交易.当transactional标志设置为true 时,服务会处理事务(默认值为true).

另一方面,当您从中访问域类时,src/groovy必须使用withTransaction块来手动处理事务.

Book.withTransaction{status->
    def book = Book.findByTitle("Groovy in Action")
    book.title = "Grails in Action"
    book.save()

    status.setRollbackOnly() //Rolls back the transaction
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅事务处理.