2017-05-22 78 views
2

我有一個Spring Data Rest項目實現的以下域類。Spring Data Rest - PUT不適用於關聯的引用類型?

@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來創建Address資源。

{ 
    "houseName":"Some House", 
    "apartmentNumber":"13 B", 
    "city": "http://localhost:8080/city/1" 
    "country":"http://localhost:8080/countries/1" 
} 

當我發送一個PUT請求到端點http://localhost:8080/addresses/1與以下JSON,爲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; 
} 
+0

你傳入字符串值在「城市」和「國家」取代的資源,但你已經聲明他們作爲用戶定義的數據類型的城市,國家.. –

+0

但它們是URIs,所以春天的數據休息會知道如何解除引用 –

+0

請分享國家和城市實體類。 –

回答

0

如果您正在使用Hibernate作爲JPA提供者,那麼你就必須讓知道的實體如何映射在兩邊,並指出它在子實體中的映射方式,這將關注如何在a中管理關係交易。

編輯和更新:

//市級

@Entity 
public class City { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = "city_id") 
    private Long cityID; 

    @Column(name = "city_name") 
    private String cityName; 

    @ManyToOne 
    private Country country; 

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "city", orphanRemoval = true) 
    private List<Address> addresses; 
} 

//國家類

@Entity 
public class Country { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = "country_id") 
    private Long countryID; 

    @Column(name = "country_name") 
    private String countryName; 

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "country", orphanRemoval = true) 
    private List<City> cities = new ArrayList<>();; 

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "country", orphanRemoval = true) 
    private List<Address> addresses; 
} 

使用Patch:如果要更新資源的一部分,資源和關係的子集

使用PUT:如果你有一個全新的表示

+0

我試過這種方式,但它不工作。 –

+0

更新了答案。請檢查並讓知道。 –

相關問題