I have some code that I want to run when a domain class object is created; in Java, I would include this code on the constructor. How can I do it in Groovy/Grails?
Thanks.
A domain class fulfills the M in the Model View Controller (MVC) pattern and represents a persistent entity that is mapped onto an underlying database table. In Grails a domain is a class that lives in the grails-app/domain directory.
GORM is the data access toolkit used by Grails and provides a rich set of APIs for accessing relational and non-relational data including implementations for Hibernate (SQL), MongoDB, Neo4j, Cassandra, an in-memory ConcurrentHashMap for testing and an automatic GraphQL schema generator.
You can add a constructor to domain class but you also have to add the default no-arg constructor if it is not already present.
//Domain Class
class Author {
String name
Author() {
//Execute post creation code
}
Author(String _name) {
name = _name
//Execute post creation code
}
}
On the other hand, domain classes are POGOs so you can also use the map constructors if there is no extra logic that needs to be executed on object creation. Without adding any constructors you can also instantiate Author
as:
Author(name: 'John Doe')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With