Grails REST POST失败,元素具有备用标识符列



这是我正在处理的一个真实项目的简化示例。我有以下域。

class PhoneNumber {
String cn
PhoneType phoneType
String phoneNumber
static constraints = {
}
}
class PhoneType {
String phoneType
String cn
static constraints = {
}
static mapping = {
id name: 'cn'
id generator: 'uuid'
}
}

简单,一部手机,有一种手机类型。

PhoneType使用cn 的备用id列

我使用grails generate-all PhoneType PhoneNumber生成默认REST控制器

我正在使用一个休息配置文件项目。我可以创建一个PhoneType。

curl 'http://localhost:8080/phoneType'  -H 'Content-Type: application/json' -X POST -d '{"phoneType":"gg"}'
{"cn":"2a10618564d228300164d234a4980003","phoneType":"gg"}

问题是,我无法使用REST创建具有此PhoneType的PhoneNumber。如果我不指定备用ID(使用默认的"ID"列(,我可以。

curl 'http://localhost:8080/phoneNumber'  -H 'Content-Type: application/json' -X POST -d '{"cn":"1","phoneNumber":"9995551212", "phoneType":{"cn":"2a10618564d228300164d234a4980003"}}'
{"message":"Property [phoneType] of class [class PhoneType] cannot be null","path":"/phoneNumber/index","_links":{"self":{"href":"http://localhost:8080/phoneNumber/index"}}}

尽管这适用于

curl 'http://localhost:8080/phoneNumber'  -H 'Content-Type: application/json' -X POST -d '{"cn":"1","phoneNumber":"9995551212", "phoneType":{"id":"2a10618564d228300164d234a4980003"}}'

我想知道这是否应该起作用,并且是框架中的一个错误,或者是否需要一些额外的配置来启用grails中没有"id"作为标识符的REST资源。

提前感谢您的指点。

您可以尝试将id设置为String或UUID(或任何您需要的(。

class PhoneType {
String phoneType
String cn = UUID.randomUUID().toString()
static constraints = {
}
static mapping = {
id name: 'cn'
id generator: 'uuid'
}
}

我认为你的问题与id无关。默认情况下,grails的属性是强制性的(nullable: false)。在JSON中,您没有给出PhoneType域的phoneType属性,并且会得到验证错误。您应该在JSON中添加phoneType属性。尝试发送以下JSON: { "cn": "1", "phoneNumber": "9995551212", "phoneType": { "cn": "2a10618564d228300164d234a4980003", "phoneType": "gg" } }

或者,如果不需要域PhoneType的属性phoneType,则在域中定义如下:

static constraints = {
phoneType nullable: true
}

最新更新