Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Domain class constructors in Grails?

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.

like image 521
user2624442 Avatar asked May 26 '14 23:05

user2624442


People also ask

What is Grails domain class?

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.

What is Grails Gorm?

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.


1 Answers

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')
like image 198
dmahapatro Avatar answered Oct 02 '22 13:10

dmahapatro