Domain class constructors in Grails?

I have code that I want to run when a domain class object is created; in Java, I would include this code in the constructor. How to do it in Groovy / Grails?

Thank.

+4
source share
3 answers

Have you seen this page about groovy constructors? I have had the success of adding map constructors to Grails domain classes using this technique.

. Grails ( , , ), , . , .

+3

, no-arg , .

//Domain Class
class Author {
    String name

    Author() {
        //Execute post creation code
    }

    Author(String _name) {
        name = _name

        //Execute post creation code
    }
}

, - POGO, , , . , Author :

Author(name: 'John Doe')
+6

Depending on the specific use case, you can use GORM events ...

http://docs.grails.org/3.1.1/guide/single.html#5.5.1

So you can use

def beforeInsert() {
    doMyCustomThing()
}

def onLoad() {
    doMyCustomThing()
}

There are several other options, including Hibernate events and custom GORM events.

0
source

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


All Articles