Grails 3.2 - 列出域类中不可为空的字段名称

  • 本文关键字:字段 Grails grails grails-orm
  • 更新时间 :
  • 英文 :


如何获取不可为空的域类的字段名称列表?

例如,在以下域中:

class MyDomain {
String field1
String field2
String field3
String field4
static constraints = {
field2 nullable: true
field3 nullable: true
}
}

如何在控制器中取回['field1','field4']列表?

我正在验证 CSV 中的行,并且某些行信息与域中存储的信息不同,因此最好获取字符串名称列表,而不是绑定到带有排除项的命令对象。

您可以使用constrainedProperties.它提供了特定域类的所有约束。

现在你只需要非空约束,然后过滤掉它的结果。

例:

MyDomain.constrainedProperties.findResults { it.value.nullable ? null : it.key }

输出:

['field1','field4']

对于圣杯 2.x 用户:

MyDomain.getConstraints().findResults { it.value.nullable ? null : it.key}

您需要使用 PersistentEntity API

Set<String> propertyNames = [] as Set
for (PersistentProperty prop: MyDomain.gormPersistentEntity.persistentProperties) {
if (!prop.mapping.mappedForm.nullable) {
propertyNames.add(prop.name)
}     
}

您可能需要根据需要排除版本或时间戳属性等内容。

最新更新