JACKSON REST API仅在ManyToOne中添加具有其ID的实体字段 [英] JACKSON REST API Add Entity Field with its id Only in ManyToOne

查看:76
本文介绍了JACKSON REST API仅在ManyToOne中添加具有其ID的实体字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Spring Rest API有点陌生.我有两个具有单向多对一关系的实体.

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
}

假设我在城市表中已经有一些城市.当我想使用http post方法添加城市ID为2的新用户时,我必须执行以下操作:

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

如您所见,我必须先将cityId分组到city实体中.不进行分组怎么办?像这样:

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
}

推荐答案

您可以使用@JsonUnwrapped

用于指示应序列化属性的注释 解开";也就是说,如果将其序列化为JSON对象,则其 而是将属性包含为其包含的属性 对象.

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.

示例代码:

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

这篇关于JACKSON REST API仅在ManyToOne中添加具有其ID的实体字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆