Grails: What is the best way to access domain classes from src / groovy class?

The Grails FAQ says the following:

Q: How can I access domain classes from sources in src / groovy?

Sometimes you develop some utility classes that live in src / groovy and that you intend to> use from services and other artifacts. However, since these classes are precompiled by Grails, it’s not possible to instantiate them and write things like Book.findByTitle ("Groovy in> Action"). But, fortunately, there is a temporary solution, since this can be done:

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

// ...

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

An application MUST complete bootstrap before the dynamic Gorm methods work correctly.

However, it seems that I can import domain objects directly and use the GORM methods in my src / groovy classes without any problems, for example:

Book.findByTitle("Groovy in Action") 

Since ApplicationHolder is deprecated, this tip should be deprecated, but are there any other reasons to avoid using domain classes directly from src / groovy?

+6
source share
1 answer

You are correct, referring to outdated information. You can use domain classes inside classes defined in src/groovy .

The only downside: you have to handle transactions manually. Conversely, services inside grails-app/services passes the transaction by default. Services serve transactions if the transactional flag is set to true (by default, this value is not specified by anything).

On the other hand, when you access domain classes from src/groovy , you need to use the withTransaction block to process transactions manually.

 Book.withTransaction{status-> def book = Book.findByTitle("Groovy in Action") book.title = "Grails in Action" book.save() status.setRollbackOnly() //Rolls back the transaction } 

See withTransaction for details .

+5
source

Source: https://habr.com/ru/post/947682/


All Articles