【发布时间】:2016-12-23 20:19:29
【问题描述】:
我正在尝试为基于角度的 CRUD 应用程序(脚手架,但客户端,使用角度)编写生成器
其中一部分是从 GORM 中提取元信息 现在,显然我已经碰壁了。
我想处理 ID 字段不是生成,而是由应用程序管理的情况。 假设我有一个类定义,例如:
@Resource(readOnly = false, formats = ['json', 'xml'])
class Phone {
int age
String phoneId
String imageUrl
String name
String snippet
static mapping = {
id name: 'phoneId', generator: 'assigned'
}
static constraints = {
snippet(nullable: true, maxSize: 2000)
}
}
我想检索用作此类标识符的字段,此处应为“phoneId”。
但如果我要求:
grailsApplication.getDomainClass(com.phonecat.Phone.getName()).identifier
我得到的是一个属性,称为 Long 类型的“id”:
DefaultGrailsDomainClassProperty@6e59cb9b name = 'id', type = Long, persistent = true, optional = false, association = false, bidirectional = false, association-type = [null]]
我是否误用了 getIdentifier 方法? 有什么我错过的吗? 还是我在 Grails/GORM 中遇到了错误?
为了完整起见,这是我正在使用的 GORM 版本(据我所知...最近在 gorm 方面发生了很多变化...):
来自 build.groovy:
compile "org.grails.plugins:hibernate5"
compile "org.hibernate:hibernate-core:5.1.2.Final"
compile "org.hibernate:hibernate-ehcache:5.1.2.Final"
另外,我正在使用 grails 控制台插件来运行这些测试:
runtime 'org.grails.plugins:grails-console:2.0.6'
(我觉得真的很棒) 但可能同样可以在普通命令行控制台中运行。
这是我使用的代码:
import com.phonecat.*
println grailsApplication.getDomainClass(Phone.getName()).identifier
def d = grailsApplication.getDomainClass(Phone.getName())
println "${d.class} ${d.clazz.name} ${d.identifier}"
def pd = Phone.findAll().each {c ->
println "${c.id} ${c.phoneId}"
}
null
问题是:假设(实际上恰好是......)我正在编写一个插件来检索有关域类的元信息;我如何从 GORM 获取该类已分配字段“phoneId”作为唯一标识符的信息,这是我在通过 REST 查询资源时应该查看的值?
【问题讨论】:
-
您是否尝试将
String phoneId更改为String id?此外,请记住从约束中删除phoneId。 -
@Michael_Szulc: 约束中的 phoneId() 只是为了确保在使用脚手架时呈现字段的顺序。确实,它们对这个问题毫无用处。我尝试了您的建议,在这种情况下,标识符方法正确报告了名称为“id”的 id 并键入 String。但这不能解决我的问题:我正在尝试修改我的模型。我实际上正在编写一个插件,它将检索我的模型的元信息(因此,标识符字段也是如此)。所以我想要一种方法来检索任何人作为唯一标识符给出的字段名称