获取与给定GORM域对象关联的持久属性列表的最佳/最简单方法是什么?我可以获取所有属性的列表,但此列表包含非持久性字段,例如class
和constraints
。
目前我正在使用此功能并使用我创建的列表过滤掉nonPersistent
属性列表:
def nonPersistent = ["log", "class", "constraints", "properties", "errors", "mapping", "metaClass"]
def newMap = [:]
domainObject.getProperties().each { property ->
if (!nonPersistent.contains(property.key)) {
newMap.put property.key, property.value
}
}
似乎必须有一种更好的方法来获得持久性属性。
答案 0 :(得分:47)
试试这个:
import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass
...
def d = new DefaultGrailsDomainClass(YourDomain.class)
d.persistentProperties
这是指向GrailsDomainClass的Grails API的链接(它是旧版本的链接;经过一些快速搜索后我找不到更新的版本)。它有一个getPersistentProperties()
(在上面的代码片段中使用)。您可以遍历API文档以查看其他可能对您有用的方法。
如果您想要一个示例,请执行grails install-templates
,然后查看src/templates/scaffolding/create.gsp
。在那里有一个块,它遍历持久域属性。
答案 1 :(得分:13)
现在(转向Grails 2.x)你甚至不必实例化new DefaultGrailsDomainClass(...)
并避免不必要的代码执行。所有域类对象都注入了属性domainClass
:
def domainObject = new YourDomain()
domainObject.domainClass.persistentProperties
或者,如果您没有域类对象,则可以通过域类名从应用程序上下文获取DefaultGrailsDomainClass
- 每个域类都有一个注册为Spring bean的DefaultGrailsDomainClass。因此,您可以使用Holders
(假设您的域名为'Foo'):
def defaultGrailsDomainClass = Holders.applicationContext.getBean("FooDomainClass")
defaultGrailsDomainClass.persistentProperties
答案 2 :(得分:6)
截至grails 3.3.0
应重写所有使用
GrailsDomainClass
或GrailsDomainClassProperty
类的代码以使用映射上下文api。要开始,请注入
的详细信息,请参阅api文档。grailsDomainClassMappingContext
bean。有关MappingContext
,PersistentEntity
(GrailsDomainClass)和PersistentProperty
(GrailsDomainClassProperty)
例如:
class MyService {
def grailsDomainClassMappingContext //inject
def accessDomainProperties(Class clazz) {
PersistentEntity entityClass = grailsDomainClassMappingContext.getPersistentEntity(clazz.name)
List<PersistentProperty> persistentPropertyList = entityClass.persistentProperties
persistentPropertyList.each { property ->
println property.name
}
}
}
希望这有助于某人。