1

What I want to do is add (POST) resource with automaticly generated id. I added annotations and my model looks like this

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String brand;

Question is why when I POST some value without id for example:

{
    "brand": "sony"
}

I GET automaticly id = 0:

{
    "id": 0,
    "brand": "sony"
}

And if I post more resources without calling id they all have id = 0 (so it's not unique).

What I do wrong?

degath
  • 1,530
  • 4
  • 31
  • 60

1 Answers1

1

I GET automaticly id = 0:

That is because you are using a primitive data type long and its default value is 0.

And the serialization-deserialization of such fields would end up appending the default value of the primitive data types if not assigned explicitly.

In cases where you need to exclude such fields when there is not value set, you might intend to use Long(reference type) instead.

Naman
  • 27,789
  • 26
  • 218
  • 353
  • Changing type for Long creates an error when i try to GET resources. "error": "Internal Server Error", "exception": "org.springframework.http.converter.HttpMessageNotWritableException", "message": "Could not write content: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[3]->spring.degath.model.Phone[\"id\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[3]->spring.degath.model.Phone[\"id\"])", "path": "/phones/" } – degath Oct 07 '17 at 13:01
  • @degath As pointed in the answer *where you need to exclude such fields* is when you shall use `Long` and then mark such fields with annotations similar to `Include.NonNull`. Or else you can continue to make use of `long` with a default value of 0. There isn't any harm in it either. Depends on your API implementation further. – Naman Oct 07 '17 at 13:03
  • Oh, I understand now why it is a default value 0, but the question is what to do to get auto incremented id while POST request (I expected that annotation @GeneratedValue(strategy = GenerationType.IDENTITY will do it for me, but seems like I've got wrong thinking) – degath Oct 07 '17 at 13:46
  • @degath Well that wasn't stated in the question though https://stackoverflow.com/questions/36388919/auto-generate-id-in-spring-mvc can help you in that case. – Naman Oct 07 '17 at 14:03
  • thanks a lot, I'm accepting your answer obviously and again thanks for a lot of forbearance. You made my day :) – degath Oct 07 '17 at 14:14