【发布时间】:2014-07-14 03:57:51
【问题描述】:
我正在使用 JAX-RS 和 JAXB 开发 RESTful 服务。我有一个Complain 类,以下是它的精简版:
@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;
}
}
注意:我已经用@XmlTransient 注释装饰了getCommentCollection,因为当我在@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 时,我需要cmets 出现在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>
由于我使用 @XmlTransient 注释装饰了 getCommentCollection,因此当我在 @Path("/{id}") 寻找特定的 Complain 时无法获得 cmets。我怎样才能做到这一点?
【问题讨论】:
-
使用
@XmlTransient注释是一个编译时决定,因此您不能在运行时动态更改它。您可以映射到有限的视图(通过第二个类或将 commentCollection 设置为 null)或查看How to conditionally serialize with JAXB or Jackson 讨论的解决方案。 -
@lefloh,如果你能告诉我如何映射到有限的视图,我将不胜感激,我是 JAX-RS 的新手。
标签: java web-services rest jaxb jax-rs