2017-01-24 58 views
0

我有幾個成員類,以及相關的getter和setter方法:如何通過RestTemplate通過嵌入式成員進行POST?

public class Tester implements Serializable { 
    @Column(name="ID", nullable=false, unique=true) 
    @Id 
    @GeneratedValue(generator="LOCATION_FACILITYTYPE_ID_GENERATOR") 
    @org.hibernate.annotations.GenericGenerator(name="LOCATION_FACILITYTYPE_ID_GENERATOR", strategy="native") 
    private int ID; 

    @Column(name="Value", nullable=false, unique=true, length=4) 
    private String value; 

    @Column(name="Name", nullable=false, unique=true, length=8) 
    private String name; 

    @ManyToOne(targetEntity=location.FacilityType.class, fetch=FetchType.LAZY)  
    @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.LOCK}) 
    @JoinColumns({ @JoinColumn(name="FacilityTypeID", referencedColumnName="ID", nullable=false) }) 
    private location.FacilityType facility; 

在JUnit中,我試圖測試創建一個測試元素:

Tester trythis = new Tester(); 
    trythis.setName("Herewe"); 
    trythis.setValue("wow1"); 
    Tester jnode = restTemplate.postForObject(TestBase.URL + "tester/", trythis, Tester.class); 

可正常工作。但是,如果我用這樣的代碼,包括嵌入式成員:

FacilityType ft = new FacilityType();  
    ft.setValue("AL"); 
    ft.setName("2adamlec"); 
    Tester trythis = new Tester(); 
    trythis.setName("Herewe"); 
    trythis.setValue("wow1"); 
    trythis.setFacility(ft); 
    Tester jnode = restTemplate.postForObject(TestBase.URL + "tester/", trythis, Tester.class); 

其中具有價值內嵌構件= AL還沒有出現在數據庫中,我仍然得到的測試表中創建一個新的行.. 。但測試人員的值和名稱列填充了爲FacilityType定義的值(AL和2adamlec)。

請注意,我們正在使用FacilityType和Tester的JPARepository框架。 CRUD功能因此在「封面」下處理,我無法調試POST處理。我想知道這是否與GET測試人員數據只會返回JSON回覆中的原始字段相關,因爲沒有爲FacilityType定義投影。

我做錯了什麼導致FacilityType字段被保存來替代Tester表中所需的Tester字段?

回答

0

簡短的回答:創建項目時,必須提供與服務器預期相同的JSON格式的數據。如果您有嵌入類,則必須創建一個類,其中facility成員是一個用於存放URL的字符串,然後將該成員設置爲與嵌入類的現有實例相對應的URL。在接收端,你還需要一個新的類是這樣的:

public class FMT_Tester_RCV { 
    public FMT_Tester_RCV() { } 

    private String value; 
    private String name; 
    private Integer id; 
    private Integer ormid; 
    private JsonNode _links; 

在那裏你可以旅行下來JsonNode獲得的鏈接嵌入類實例。