2014-05-25 29 views
1

我正在開發一個使用JAX-RS和JAXB的RESTful服務。我有一個Complain類,以下是它的條紋縮小版本:JAX-RS和JAXB @XmlTransient

@Entity 
@Table(name = "complain") 
@XmlRootElement 
public class Complain implements Serializable { 

    private String title; 
    private String description; 

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "complainidComplain") 
    private Collection<Comment> commentCollection; 

    @XmlTransient 
    public Collection<Comment> getCommentCollection() { 
    return commentCollection; 
    } 
} 

注:我飾getCommentCollection@XmlTransient註釋,因爲我不希望看到的時候我正在尋找所有的抱怨發表評論在@Path("/")

example.com/api/complain/

<complains> 
<complain> 
    <title>Foo</title> 
    <description>Foo is foo</description> 
</complain> 
<complain> 
    <title>Bar </title> 
    <description>Bar is bar</description> 
</complain> 
</complains> 

但是當我在@Path("/{id}")尋找特定Complain,我需要的評論出現在XML輸出。

example.com/api/complain/1

<complain> 
<title>Foo</title> 
<description>Foo is foo</description> 
<comments> 
    <comment> Yes, i agree </comment> 
    <comment> Lorem if foo </comment> 
</comments> 
</complain> 

既然我已經裝飾getCommentCollection@XmlTransient註釋,當我在@Path("/{id}")尋找特定Complain我不能評論。我怎樣才能做到這一點?

+2

使用''@ XmlTransient'''進行註釋是一個編譯時決定,因此您不能在運行時動態更改它。您可以映射到有限視圖(通過第二個類或將commentCollection設置爲null)或查看[如何有條件地使用JAXB或Jackson序列化]中討論的解決方案(http://stackoverflow.com/questions/12941398 )。 – lefloh

+0

@lefloh,如果你能告訴我如何映射到有限的視圖,我會很感激,我是JAX-RS的新手。 –

+0

我加了一個答案。 – lefloh

回答

2

使用@XmlTransient註解是一個編譯時間的決定因此您不能在運行時動態更改它。正如How to conditionally serialize with JAXB or Jackson所述,您可以使用Jacksons JsonViewMOXy's external mapping-files

如果你不想改變你的序列化器,你可以將Complain映射到一個有限的類,例如, ComplainPreview,它只有屬性titledescription。在使用JAX-RS資源方法返回之前,您也可以簡單地將commentCollection設置爲null

最後(也許最乾淨)的解決方案:只提取你想從數據庫返回的數據。因此,您需要針對兩種用例的不同查詢。你可以例如使用Constructor Expression爲第一個:

select new com.yourcompany.Complain(c.title, c.description) from Complain c 

不要忘記添加對應的構造。