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

时间:2018-07-25 16:26:03

标签: rest grails grails-3.3

这是我正在从事的真实项目的简化示例。 我有以下领域。

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"}}'

我想知道这是否应该起作用并且是框架中的错误,或者是否需要一些其他配置才能在没有“ id”作为标识符的grails中启用REST资源。

预先感谢任何指针。

2 个答案:

答案 0 :(得分:1)

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

class PhoneType {

  String phoneType
  String cn = UUID.randomUUID().toString()
  static constraints = {
  }

  static mapping = {
      id name: 'cn'
      id generator: 'uuid'
  }
}

答案 1 :(得分:0)

我认为您的问题与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
}