Mandar Pathak
Mandar Pathak

Reputation: 870

Prevent binding of JAXB elements when object is created

I have a class as follows:

    @XmlRootElement(name="User")
    @XmlAccessorType(XmlAccessType.NONE)
    public class User {

    private int id;
    private String name;

    public User() { }

    @XmlAttribute
    public int getID() {
      return id;
    }

    public void setID() {
      this.id = id;
    }

    @XmlElement
    public String getName() {
      return first + " " + last;
    }

    public void setName(String name) {
      this.name = name;
    }

    // other class code   
  }

I am using this class for a JAX-RS service. When a client wishes to create a new user, an XML representation of the following format must be sent.

<User>
  <name>John Doe</name>
</User>

On receiving such a snippet, my service creates a new user correctly. However, if the client includes an ID attribute for the user (e.g. <User id="100">...</User>) the id value of the attribute is assigned to the the user.

As you can imagine, I wish to use the ID field as a primary key of the User class and do not wish for a user to be able to specify it. However, when I return a representation of the User instance (also in XML), I wish to be able to specify the ID as an attribute.

How do I achieve this?

Upvotes: 1

Views: 276

Answers (1)

bdoughan
bdoughan

Reputation: 149057

There are a few ways this could be done:

Option #1

You could null the ID field out when a create operation is done.

@POST
@Consumes(MediaType.APPLICATION_XML)
public void create(User user) {
    user.setId(0);
    entityManager.persist(customer);
}

Option #2

Alternatively you could have a second User class without an id field, that you use for the parameter of the create operation:

@POST
@Consumes(MediaType.APPLICATION_XML)
public void create(UserWithoutID userWithoutID) {
    User user = new User();
    // Copy from userWithoutID to user
    entityManager.persist(customer);
}

Option #3

If you are using property access, another option is to only provide a getter for your id property. Then JAXB will include in on the write (marshal), but not on a read (unmarshal).

Upvotes: 1

Related Questions