简体   繁体   中英

When and why should nullable or/and blank constraints in a grails domain class?

I am a bit new to grails and I'd like to get a clear understanding of how to use 'nullable' and 'blank' constraints in a grails domain class.

An example is;

static constraints = { name nullable: true }

static constraints = { name blank: true }

static constraints = { name nullable: true, blank: true }

What do each of these mean and how best can they be applied?

All properties are not-null by default, so generally the only time you use the nullable constraint is when you want to allow nulls, ie nullable: true .

Moreover, by default Grails databinding will convert blank strings to null, which effectively means that blank: false is applied by default (because blanks are converted to null, and nulls are prohibited).

There are some theoretical cases wherein it would be necessary to explicitly specify blank: false , eg if a property is set to a blank string after databinding. However, these are very unlikely to occur in practice, so ignoring some edge cases it's reasonable to assume that blank: false, nullable: false are applied by default.

Well, at first you should look into the docs .
Second:
Nullable is already set by default to false. If you want some value to be nullable, then you write name nullable: true .
Nullable means that when creating an object, that value can be left null (nothing inputted). Blank - when you will create ie form for objects param input and you left a field empty, it will save with no errors and accept empty value.
Long story short - Blank is for forms to accept empty. Nullable is for the coded object to be saved without value.
You can also see this post .

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