0

This is a valid Entry object retrieved from a GET request http://domain/entry/{id}:

{
    "id": 1,
    "description": "ML Books",
    "dueDate": "2017-06-10",
    "paymentDate": "2017-06-10",
    "note": "Distribution de lucros",
    "value": 6500,
    "type": "INCOME",
    "category": {
        "id": 2,
        "name": "Food"
    },
    "person": {
        "id": 3,
        "name": "User",
        "active": true,
        "address": {
            // properties suppressed for better reading
        }
    }
}

In a POST request I want to save the foreing objects Category and Person just sending the respective Id's, like this:

{
    "description": "NEW ENTRY",
    "dueDate": "2019-06-22",
    "paymentDate": "2019-06-22",
    "note": "Coloured pens",
    "value": 10,
    "type": "INCOME",
    "categoryId": 5,
    "personId": 5
}

To save the objects without Spring saying the person and category objects were null, I've added @JsonIgnore to them in the model, and followed this thread.

It partially worked:

  • now it saves de object just with the Id
  • but not retrieves the object in GET requests

Now, when retrieving a Entry with the same GET request http://domain/entry/{id}:

{
    "id": 23,
    "description": "Pens",
    "dueDate": "2019-06-22",
    "paymentDate": "2019-06-22",
    "note": "Coloured pens",
    "value": 10,
    "type": "INCOME",
    "categoryId": null, // It supposed to bring the entire object
    "personId": null // It supposed to bring the entire object
}

PS: categoryId and personId are marked with @Transient, that's why it are null.

So as the title states, I want to ignore the properties Category and Person just in POST request (saving them), not in GET requests (retrieving them).

Any help will be welcome. Thanks in advance

tomrlh
  • 1,006
  • 1
  • 18
  • 39
  • You're using the same class to represent 3 very different things: 1. your persistence model, 2. the JSON data that your HTTP API promises to return (and which shouldn't change if you decide to change your mmind about the implementation of your persistencemodel), 3. the JSON data that your REST API expects to create an entry. Use three different classes for each of these three different things, and everything will be much clearer, simpler, flexible, because they're decoupled. – JB Nizet Jun 22 '19 at 16:58
  • So you're saying to create different models, for each case (GET, POST)? The annotations from Spring/Jackson can't handle this? – tomrlh Jun 22 '19 at 17:41

1 Answers1

1

Jackson have added READ_ONLY and WRITE_ONLY annotation arguments for JsonProperty. So you could also do something like:

@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@Id
@GeneratedValue
private  Long  id;
Aravind
  • 1,145
  • 6
  • 18
  • 44