【问题标题】:JAX-RS, with JAXB @XmlTransientJAX-RS,带有 JAXB @XmlTransient
【发布时间】: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


【解决方案1】:

使用@XmlTransient 进行注释是一个编译时决定,因此您不能在运行时动态更改它。正如How to conditionally serialize with JAXB or Jackson 所讨论的,您可以使用Jacksons JsonViewMOXy's external mapping-files

如果您不想更改您的序列化器,您可以将Complain 映射到一个有限的类,例如ComplainPreview 只有属性 titledescription。您也可以简单地将 commentCollection 设置为 null,然后在您的 JAX-RS 资源方法中返回它。

最后一个(也许是最干净的)解决方案:只获取您想从数据库返回的数据。因此,您需要针对两个用例进行不同的查询。例如,您可以使用Constructor Expression 作为第一个:

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

不要忘记添加对应的构造函数。

【讨论】:

    猜你喜欢
    • 2015-08-02
    • 2013-09-01
    • 2023-04-09
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多