2014-03-25 51 views
0

我有兩個在數據庫中有關係的JPA註釋類。我使用Jersey來公開REST api。使用關係的ID與Jackson反序列化JPA關係

//package and imports 

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) 
@JsonIgnoreProperties(ignoreUnknown = true) 
@Entity 
public class Parent { 
    @Id 
    @GeneratedValue 
    private Long id; 
    private String name; 

    //Getters and setters 

} 

//package and imports 

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) 
@JsonIgnoreProperties(ignoreUnknown = true) 
@Entity 
public class Child { 
    @Id 
    @GeneratedValue 
    private Long id; 
    private String name; 

    @ManyToOne 
    private Parent parent; 

    //Getters and setters 
} 

當我在http://localhost/children執行GET請求,我得到以下JSON:

[{ 
    "id": 1, 
    "name": "child1", 
    "parent": { 
    "id": 1, 
    "name": "parent" 
    } 
}, { 
    "id": 2, 
    "name": "child2", 
    "parent": { 
    "id": 1, 
    "name": "parent" 
    } 
}] 

這是利用傑克遜序列化JSON數據庫模型。

當我執行POST請求http://localhost/children使用以下有效載荷增加一個孩子:

{ 
    "name": "child3", 
    "parent": { 
    "id": 1 
    } 
} 

孩子被持久化到數據庫,但有父母名字null值。我看到這個的時候我就http://localhost/children

[{ 
    "id": 1, 
    "name": "child1", 
    "parent": { 
    "id": 1, 
    "name": "parent" 
    } 
}, { 
    "id": 2, 
    "name": "child2", 
    "parent": { 
    "id": 1, 
    "name": "parent" 
    } 
}, { 
    "id": 3, 
    "name": "child3", 
    "parent": { 
    "id": 1 
    } 
}] 

執行另一個GET我用了@JsonIdentityInfo/@JsonIdentityReference方法,但這並不解決問題。我不想將整個Parent對象作爲json加入我的POST請求中,以添加一個子對象,但只想使用Parent ID。有什麼想法嗎?

回答

0

我最終通過使用我的EntityManager的合併方法來解決它,而不是堅持。然後所有的數據被髮送回客戶端。