gpt4 book ai didi

rest - 如何通过 REST 和 JAX-RS 为父子实体建模

转载 作者:行者123 更新时间:2023-12-04 22:52:52 24 4
gpt4 key购买 nike

我正在研究基于 REST 的 API,并且在弄清楚代表父/子关系的规范方式是什么时遇到了一些麻烦。 (我在 CXF 中编写 bean 并使用 JAX-RS 和 JAXB。我从 CXF 提供的基本示例开始)

我的问题是假设您有一个 Foo 和一个 Bar。 Foo 和 Bar 之间存在 1-N 关系,即 1 Foo 有许多 Bar。我的问题是,找出 Bars a Foo 有什么的规范方法是什么?访问 Foo 拥有的 Bar 资源的规范方式是什么?

我已经发现,例如,我可能会在以下位置列出 Foos:

获取 http://xxx/fooservice/foos

并在单个 foo 上操作:

放置/更新/删除 http://xxx/fooservice/foo/ {傻瓜}

但是我如何列出 Foo 121 拥有的 Bars?我如何访问它们?我注意到似乎默认的 JAXB 编码器不输出 Collections 只是一个 bean 的属性,所以如果 Foo 是:


- 字符串 ID
- 字符串名称
- 收藏栏

JAXB 输出如下:

123>/id> foo name <--注意没有bars属性

这是有问题的,因为没有办法让客户合理地知道 Foo 有 Bars,除非它“只是知道”(这对我来说似乎很糟糕)。因此,虽然我可以想象使用以下方法获取条形列表:

获取 http://xxx/fooservice/foo/121/bars

如果实体的输出没有说明任何内容,客户端如何知道 Foo 有 Bars?现在假设客户端确实获得了列表,那么实体操作似乎类似于:

获取/删除/更新 http://xxx/fooservice/foo/121/bar/435

这将访问 Foo 121 拥有的 Bar 435。

最佳答案

你想做的事当然是可能的。设计资源的一种方法是:

/foo
# A list of all the Foo resource names (not representations).

/foo/{fooid}
# A detailed representation of a particular Foo, including
# a list of all that Foo's Bar resource names (not representations).

/foo/{fooid}/bar/{barid}
# A detailed representation of a particular Bar.

您可能会遇到这样的情况,即 Bars 在特定 Foo 之外没有实际存在(如在采购订单的主文件及其包含的详细信息行中)。如果是这种情况,并且每个 Foo 都没有那么多 Bar 数据与之配套,您可以在 Foo 表示中返回完整的 Bar 详细信息:
/foo
# A list of all the Foo resource names (not representations).

/foo/{fooid}
# A detailed representation of a particular Foo, including
# full details on each of its Bars.

您通常希望 REST 资源的粒度更粗。请注意,如果您选择此选项,那么要修改 Foo 的 Bars,您将 GET Foo,修改 Foo 表示中的 Bars,然后将 Foo 放入。

不确定您的序列化 XML 表示发生了什么,您应该使用相关代码创建第二个问题。

关于rest - 如何通过 REST 和 JAX-RS 为父子实体建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1786795/

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