Is this a valid use of Grails transients?

I have a domain object on which I want to store several things that exist only at runtime. I looked at the documentation and found the transients keyword, which, at first glance, was what I was looking for. This is what my domain object looks like ...

 class Contact { def Seeker def beforeInsert() { initiatedDate = new Date() } Date initiatedDate Date acceptedDate static transients = ['pal'] Seeker pal } 

where Seeker is the groovy class, which is not a domain object, but a placeholder for some properties.

So far, everything is in order, and my contact table does not have a pal field, as expected. In my ContactController request for a bunch of contacts c , then find their Seeker pals (details on how to remove them) and set a new object for the pal field.

 c.pal = new Seeker(); c.pal.name = otherObject.name render c as JSON 

All this works fine, except that the pal object is missing from the returned JSON.

Is this a legitimate use of transients? The docs mention that they are convenient for function-based getters and seters, but in my case I want an actual object. Should I write a getPal () and setPal () method for my object?

thanks

+4
source share
1 answer

Transients are really used to prevent fields from being stored in domain objects. (If you want to perform some initialization in the "Ad" field without placing it in your controller, you can use the onLoad () event or write the getPal () method, which overrides the default getter property). You are also right to note that the default JSON marshaller only displays persistent fields.

When rendering my domain objects, I found it useful to create JSON object marshalers so that unwanted properties would not appear, but that would also solve your temporary problem. You can do this using the JSON.registerObjectMarshaller method:

 import grails.converters.JSON ... class BootStrap { def init = {servletContext -> JSON.registerObjectMarshaller(Contact ) { def returnArray = [:] returnArray['id'] = it.id returnArray['initiatedDate'] = it.initiatedDate returnArray['acceptedDate'] = it.acceptedDate returnArray['pal'] = it.pal return returnArray } JSON.registerObjectMarshaller(Seeker) { ... } 

If you add marshalers to your BootStrap.groovy, they will be available in your controllers.

NTN

(Also found the following: http://old.nabble.com/Taggable-plugin-and-JSON-converter-ts24830987.html#a24832970 )

+7
source

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


All Articles