Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JAX-RS,带有JAXB@xmltransive_Java_Web Services_Rest_Jaxb_Jax Rs - Fatal编程技术网

Java JAX-RS,带有JAXB@xmltransive

Java JAX-RS,带有JAXB@xmltransive,java,web-services,rest,jaxb,jax-rs,Java,Web Services,Rest,Jaxb,Jax Rs,我正在使用JAX-RS和JAXB开发一个RESTful服务。我有一个投诉类,下面是它的一个分条版本: @Entity @Table(name = "complain") @XmlRootElement public class Complain implements Serializable { private String title; private String description; @OneToMany(cascade = CascadeType.ALL, mapp

我正在使用JAX-RS和JAXB开发一个RESTful服务。我有一个
投诉
类,下面是它的一个分条版本:

@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;
   }
}
但是,当我在
@Path(“/{id}”)
中查找特定的
投诉时,我需要在XML输出中显示注释

example.com/api/complaint/1

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

福
福就是福
是的,我同意
洛雷姆·伊夫·福

因为我已经用
@xmltransive
注释修饰了
getCommentCollection
,所以当我在
@Path(“/{id}”)
上查找特定的
投诉时,我无法获得注释。我怎样才能做到这一点

使用
@xmltransive
进行注释是一种编译时决策,因此您不能在运行时动态更改它。正如在上讨论的,您可以使用或

如果您不想更改序列化程序,可以将
complaint
映射到一个有限的类,例如
ComplainPreview
,该类只有属性
title
description
。在JAX-RS资源方法中返回之前,您还可以简单地将
commentCollection
设置为
null

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

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

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

使用
@xmltransive
注释是一个编译时决定,因此您不能在运行时动态更改它。您可以映射到有限视图(通过第二个类或将commentCollection设置为null),也可以查看在中讨论的解决方案。@lefloh,如果您能告诉我如何映射到有限视图,我将不胜感激,因为我是JAX-RS新手。
select new com.yourcompany.Complain(c.title, c.description) from Complain c