JAXB REST PUT 引用关联
考虑以下实体类:
Manufacturer
:代表汽车制造商(福特、沃尔沃等)并具有名称。Model
:代表型号(Fiesta、S80),有名称,由单一制造商制造。
模型中的制造商字段注释如下:
@ManyToOne
@XmlIDREF
private Manufacturer manufacturer;
然后,我定义了两个 REST 资源,用于获取和放置制造商和类型。问题出在放置 types:
@PUT
@Consumes("application/xml")
public void putModel(JAXBElement<Model> model) {
modelFacade.create(model.getValue());
}
和我尝试放置的 XML:
<model>
<name>Fiesta</name>
<manufacturer>1</manufacturer>
</model>
Manufacturer 元素指向 1
,一个 Manufacturer
的有效实例,但是,当模型被持久化时, MANUFACTURER_ID
为 null
。如何让 JAXB 也从 XML 中读取制造商的 ID?
谢谢!
Consider the following entity classes:
Manufacturer
: represents a car manufacturer (Ford, Volvo, ...) and has a name.Model
: represents a model (Fiesta, S80), has a name, and is manufactured by a single manufacturer.
The manufacturer field in the model is annotated as follows:
@ManyToOne
@XmlIDREF
private Manufacturer manufacturer;
I then have two REST resources defined for getting and putting both manufacturers and types. The problem is with putting types:
@PUT
@Consumes("application/xml")
public void putModel(JAXBElement<Model> model) {
modelFacade.create(model.getValue());
}
and the XML I try to put:
<model>
<name>Fiesta</name>
<manufacturer>1</manufacturer>
</model>
The manufacturer element points to 1
, a valid instance of Manufacturer
, however, when the Model is persisted, the MANUFACTURER_ID
is null
. How can I get JAXB to read the manufacturer's ID from the XML as well?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑添加制造商的超链接而不是 ID(以使其更加 RESTful)。请参阅这封电子邮件来自 users@jersey 邮件列表,其中有一个示例。
Consider adding a hyperlink to the manufacturer instead of an ID (to make it more RESTful). See this e-mail from the users@jersey mailing list which has an example of that.
我对类似问题给出的以下答案可能会有所帮助。它利用
XmlAdapter
将引用的对象与 ID 相互转换:要在 JAX-RS 环境中利用它来创建 RESTful 服务您需要利用 MessageBodyReader 来在传递给
Unmarshaller
的XmlAdapter
上设置 EntityManager 实例。The following answer I gave to a similar question may help. It makes use of an
XmlAdapter
to convert the referenced object to/from an ID:To leverage this in a JAX-RS environment to create a RESTful service you will need to leverage a MessageBodyReader in order to set an instance of EntityManager on the
XmlAdapter
passed to theUnmarshaller
.