1

我正在尝试为基于角度的 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 查询资源时应该查看的值?

4

1 回答 1

0

通常,如果您想检查模型的映射,您应该更喜欢 GORM API 而不是 GrailsDomainClass。为此,您需要获取对MappingContext的引用(它可以由 Spring 注入依赖项)。然后:

 PersistentEntity entity = mappingContext.getPersistentEntity(Phone.name)
 println entity.identity.name
于 2017-01-02T08:21:53.713 回答