JACKSON REST API Add Entity Field with its id Only

2020-05-01 21:19发布

问题:

I'm kinda new with spring rest api. I have two entities that have unidirectional many to one relationship.

@Entity
public class Users{
    @Id @Column(name = "user_id") @JsonProperty("userId")
    private int id;

    @ManyToOne @JoinColumn("city_id")
    private City city;

    // other fields, getters, setters
}

@Entity
public class City{
    @Id @Column(name = "city_id") @JsonProperty("cityId")
    private int id;

    private String name;

    // other fields, getters, setters
}

Suppose that I already have some cities in city table. When I want to add new user with city id 2 using http post method, I had to do something like this:

{
  "userId": 1,
  "city": {
     "cityId": 2
  }
}

As you can see I had to group cityId inside city entity first. How can I do it without grouping it? like this :

{
  "userId": 1,
  "cityId": 2
}

回答1:

You can use @JsonUnwrapped link

Annotation used to indicate that a property should be serialized "unwrapped"; that is, if it would be serialized as JSON Object, its properties are instead included as properties of its containing Object.

sample code:

@Entity
public class Users{
    @Id @Column(name = "user_id") @JsonProperty("userId")
    private int id;

    @JsonUnwrapped
    @ManyToOne @JoinColumn("city_id")
    private City city;

    // other fields, getters, setters
}