【发布时间】:2017-10-22 08:39:32
【问题描述】:
我为 Spring Data Rest 项目实现了以下域类。
@Entity
@Data
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long addressID;
private String houseName;
private String apartmentNumber;
@ManyToOne
private City city;
@ManyToOne
private Country country;
}
现在我通过发送带有以下 JSON 的 POST 创建地址资源。
{
"houseName":"Some House",
"apartmentNumber":"13 B",
"city": "http://localhost:8080/city/1"
"country":"http://localhost:8080/countries/1"
}
当我使用以下 JSON 向端点 http://localhost:8080/addresses/1 发送 PUT 请求时,houseName 的值会更新。然而,即使我为城市发送不同的 URI,城市仍然保持不变。
{
"houseName":"Another House",
"apartmentNumber":"13 B",
"city": "http://localhost:8080/city/2"
"country":"http://localhost:8080/countries/1"
}
如果我发送 PATCH 而不是 PUT,则城市值也会更新。那么我该如何解决呢?
更新 1
国家级
@Data
@Entity
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long countryID;
private String countryName;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "country", orphanRemoval = true)
private List<City> cities;
}
城市等级
@Data
@Entity
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long cityID;
private String cityName;
@ManyToOne
@JoinColumn(name = "country_id")
private Country country;
}
【问题讨论】:
-
您在“city”和“country”中传递字符串值,但您已将它们声明为用户定义的数据类型 City、Country..
-
但它们是 URI,所以 spring data rest 会知道如何取消引用它们
-
请同时分享国家和城市实体类。
-
@mephis-slayer 我已经用城市和国家类更新了问题
标签: spring rest spring-boot spring-data-rest spring-hateoas