In Grails, how can I determine if an object is temporary or not?

I have code in Grails:

def product = Product.get(5) ?: new Product()
product.isDiscounted = product.isDiscounted ?: true

The problem is that if the property is isDiscountedalready set for an existing product and it is false, I would end up changing it to true. Is it possible to check if an object is transient?

+3
source share
1 answer

In this case, create a property Booleaninstead Boolean, then the initial value will be null, and not by default - false. This will also help verify, as you can make sure that the selection falsewas intentional, and not just the default.

In general, you can use a method isAttached()(or a property style variant attached), for example

def product = Product.get(5) ?: new Product()
product.isDiscounted = product.attached ? product.isDiscounted ? true

:

def product = Product.get(5) ?: new Product(discounted: true)
+5

All Articles