![](/img/trans.png)
[英]Grails GORM domain object naming conventions for date fields, and persistence consequences
[英]Grails - how to get object domain fields without GORM additional fields?
為了對我的域類對象進行驗證,我需要獲取需要對其進行驗證的所有相關字段。
我需要的確切字段是我自己在域類中定義的字段,而不是那些由GORM定義的字段。
我需要知道如何獲得這些字段?
我的意思是,如何獲取所有沒有'id','version'和所有其他GORM生成字段的字段。
謝謝!
域類實例上的constraints
屬性為您提供了ConstrainedProperty
對象的列表,這些對象代表了按其列出的順序在域類的constraints
塊中列出的屬性(請參閱本文檔頁面的底部)。
static constraints = {
prop2()
prop1(nullable:true)
prop3(blank:true)
}
因此,只要您在constraints
塊中提到了每個屬性,就可以使用
myObj.constraints.collect { it.propertyName }
獲取屬性名稱列表(在上面的示例中,您將[prop2, prop1, prop3]
)。
您可以做幾件事。
如果您具有這樣的域類:
// grails-app/domain/com/demo/Person.groovy
class Person {
String firstName
String lastName
// notice that only firstName is constrained, not lastName
static constraints = {
firstName matches: /[A-Z].*/
}
}
您可以查詢persistentProperties屬性以獲得所有持久性屬性的列表:
def person = new Person()
def personDomainClass = person.domainClass
// this will not include id and version...
def persistentPropertyNames = personDomainClass.persistentProperties*.name
assert persistentPropertyNames.size() == 2
assert 'firstName' in persistentPropertyNames
assert 'lastName' in persistentPropertyNames
如果您想做同樣的事情,但沒有要查詢的Person類的實例,則可以執行以下操作:
def personDomainClass = grailsApplication.getDomainClass('com.demo.Person')
// this will not include id and version...
def persistentPropertyNames = personDomainClass.persistentProperties*.name
assert persistentPropertyNames.size() == 2
assert 'firstName' in persistentPropertyNames
assert 'lastName' in persistentPropertyNames
您還可以從約束圖中獲取鍵:
// this will include both firstName and lastName,
// even though lastName is not listed in the constraints
// closure. GORM has added lastName to make it non
// nullable by default.
// this will not include id and version...
def constrainedPropertyNames = Person.constraints.keySet()
assert constrainedPropertyNames.size() == 2
assert 'firstName' in constrainedPropertyNames
assert 'lastName' in constrainedPropertyNames
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.