简体   繁体   中英

Return complex type from Java Web service

I use Java Persistence, and I want a web method to return a 'portion' of an Entity class. For example, I have a Customer class that represents a record in Customer table with many fields, but I want to return just few of them. Is it possible to use mapping to do that? Or the only way is to create a new class (maybe a superclass for Customer) that has only fields I want to return? I tried binding, but it didn't work (apparently I did it in a wrong way):

@Entity  
@Table(name = "Customer", catalog = "test", schema = "")
@XmlType(name = "Customer")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")  
@XmlElement  
private Integer accountId;

@Basic(optional = false)    
@Column(name = "username")
@XmlElement
private String username;

@Basic(optional = false)
@Column(name = "password")
private String password;

I thought that if I don't add @XmlElement annotation to password field, it won't be included into result. However, I got a bunch of "Class has two properties of the same name" errors during deployment.

This is because the default behaviour for XML generation is PUBLIC_MEMBER ( http://java.sun.com/javaee/5/docs/api/javax/xml/bind/annotation/XmlAccessorType.html ).

Since you are putting the @XmlElement on the fields, it is grabbing both your public getter/setter methods AND any field w/ @XmlElement on it. What you're likely going to want to is set the XmlAccessorType to either FIELD or NONE.

Annotate the class with

@XmlAccessorType(XmlAccessType.NONE)

Then annotate the fields you want to send with

@XmlElement(name="field_name")

There's actually a JAXB issue (that I can't find the reference to right now) that basically says that if you will be reading from XML, you'll want to annotate the setters and not the fields themselves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM