Grails REST POST fails with element with alternate identifier column

69 Views Asked by At

This is a reduced example from a real project I am working on. I have the following domains.

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

Simple, a phone, with a phone type.

PhoneType uses an alternate id column of cn

I generate the default REST controllers with grails generate-all PhoneType PhoneNumber

I am using a rest profile project. I can create a PhoneType just fine.

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

The problem is I can't create a PhoneNumber with this PhoneType using REST. If I don't specify an alternate ID (using the default 'id' column), I can.

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

though this works

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

I wonder if this is supposed to work and is a bug in the framework or if there is some additional configuration required to enable working with REST resources in grails that do not have 'id' as an identifier.

Thanks in advance for any pointers.

2

There are 2 best solutions below

1
On

I think your problem isn't connected with id. By default properties of grails is mandatory (nullable: false). In your JSON you don't give the phoneType property of PhoneType domain and you get the validation error. You should add the phoneType property in your JSON. Try to send the following JSON: { "cn": "1", "phoneNumber": "9995551212", "phoneType": { "cn": "2a10618564d228300164d234a4980003", "phoneType": "gg" } }

or if the property phoneType of domain PhoneType isn't required you define it in the domain as following:

static constraints = {
   phoneType nullable: true
}
0
On

You can try to set the id as String or UUID (or anything you need).

class PhoneType {

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

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