简体   繁体   中英

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.

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')

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

This article contains a good example and highlights an important issue. If you want to disable the map constructor for a Grails domain class (not that I think that's a particularly good idea), you might try throwing a runtime exception rather than returning a new instance. Or, have your map constructor marshall the data and call one of your other constructors.

Depending on the exact use case you could use the GORM events ...

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

So you could use

def beforeInsert() {
    doMyCustomThing()
}

def onLoad() {
    doMyCustomThing()
}

There are a few other options, including Hibernate events and custom GORM events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM