gpt4 book ai didi

java - JAX-RS,带有 JAXB @XmlTransient

转载 作者:行者123 更新时间:2023-11-30 03:53:18 25 4
gpt4 key购买 nike

我正在使用 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;
}
}

注:我已经装饰了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>

但是当我正在寻找特定的Complain时在@Path("/{id}") ,我需要注释出现在 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注释当我寻找特定的 Complain 时,我无法获得评论在@Path("/{id}") 。我怎样才能实现这个目标?

最佳答案

使用@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

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

关于java - JAX-RS,带有 JAXB @XmlTransient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23852130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com