创建时嵌套对象的属性覆盖top属性

时间:2019-10-20 09:39:21

标签: java spring rest jpa spring-data-rest

我有两个具有双向 ManyToOne 关系的实体。当我尝试保存包含嵌套对象的对象时,具有相同名称的属性将被替换。

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String firstName;
    private String lastName;
    private String name;
    @OneToMany(mappedBy = "person")
    private Collection<Phone> phones;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Collection<Phone> getPhones() {
        return phones;
    }

    public void setPhones(Collection<Phone> phones) {
        this.phones = phones;
    }
}

@Entity
public class Phone {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String number;
    private String name;
    @ManyToOne
    private Person person;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}

以及使用 @RepositoryRestResource 注释扩展 PagingAndSortingRepository 的相应存储库。

人员 Phone 实体具有共同的 name 属性。当我创建新手机时( ManyToOne 关系的所有者),在 http://localhost:8080/phones 上使用有效载荷发送POST请求

{
    "number": "456765",
    "name": "Alcatel",
    "person": {
        "firstName": "Tom",
        "lastName": "Hanks",
        "name": "Tom Hanks"
    }
}

我知道这不是在REST中更新关系的方式,但是在前端,我正在使用Angular,并且那里有诸如帮助器字段之类的东西。 Phone 打字稿类中的 person ,我不想在发送之前将其无效。

我收到覆盖了 name 属性的回复

{
    "number": "456765",
    "name": "Tom Hanks",
    "_links": {
        "self": {
            "href": "http://localhost:8080/phones/3"
        },
        "phone": {
            "href": "http://localhost:8080/phones/3"
        },
        "person": {
            "href": "http://localhost:8080/phones/3/person"
        }
    }
}

当然我可以在 Phone 类的 setPerson 方法上添加 @JsonIgnore 批注,或者在发送JSON时使person属性无效,它将起作用正确,但我很好奇为什么会发生?

0 个答案:

没有答案