首页 > 解决方案 > 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 列

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

我正在使用一个休息档案项目。我可以创建一个 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 资源。

在此先感谢您的任何指点。

标签: restgrailsgrails-3.3

解决方案


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

class PhoneType {

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

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

推荐阅读