1

Here's my problem:

Say I have two entities annotated with JAX-RS annotations:

@XmlRootElement
@Entity
public Person {
  private String firstname;
  private String lastname;

  private Address address;
}

@XmlType
@Entity
public Address {
  private String street;
  private String city;
}

This will get rendered into:

<person>
  <firstname></firstname>
  <lastname></lastname>
  <address>
    <street></street>
   <city></city>
  </address>
</person>

My question therefore is:

Is it possible to annotate those entities so that the xml returned is:

<person>
  <firstname></firstname>
  <lastname></lastname>
  <street></street>
  <city></city>
</person>

i.e. properties of Address entity are treated as Person properties (without the enclosing tags)?

4

2 回答 2

2

您可以使用EclipseLink JAXB (MOXy)来做到这一点。MOXy 包含一个名为 @XmlPath 的注解,用于进行基于 XPath 的映射。self XPath (".") 会给你想要的效果:

@Entity 
@XmlAccessorType(XmlAccessType.PROPERTY) 
@XmlRootElement 
public Person { 
   private String firstname; 
   private String lastname; 
   private Address address; 

   // getter and setter for firstname/lastname 

   @XmlPath(".")
   public Address getAddress() { return address; } 

   public String getStreet() { return getAddress().getStreet(); } 

   // more getters and setters 
} 

有关使用 EclipseLink JAXB 扩展的示例,请参见:

为了使用 MOXy 作为您的 JAXB 实现,您必须在模型类中添加一个 jaxb.properties 文件,其中包含以下内容:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

顺便说一句,MOXy 还具有许多用于处理 JPA 实体的扩展:

我在我的博客上发布了一系列关于如何使用 JAX-RS 创建基于 JPA 的 RESTful 服务的示例:

于 2010-07-12T20:13:21.723 回答
0

我不完全确定您为什么要这样做,但这可能有效(未经测试)

@XmlRootElement
@Entity
@XmlAccessorType(XmlAccessType.PROPERTY)
public Person {
   private String firstname;
   private String lastname;

   private Address address;

   // getter and setter for firstname/lastname

   @XmlTransient
   public Address getAddress() { return address; }

   public String getStreet() { return getAddress().getStreet(); }

   // more getters and setters
}

@XmlType
@Entity
public Address {
  private String street;
  private String city;

  // getters and setters
}

不过,我个人此时会使用 DTO 模式。混合 ORM 和序列化注释很少是一件好事。

于 2010-07-12T10:36:40.677 回答