Question

I am using Jackson (jaxb) for JSON marshalling and unmarshalling.

For example here I have annotated address field XmlTransient because I don't want it to be mapped when person records are listed (Security and Speed concerns), address field is lazy anyway. But when a single person record is returned I want that address field to be mapped, but even fetching the address eagerly jaxb still doesn't map it. Is there any way that I can change this behaviour and map this field at runtime when the address field is annotated with @XmlTransient?

    public class Person implements Serializable {

    @Column(nullable = false, length = 50)
    private String username;

    @OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
    private Address address;

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

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

    public void setAddress(Address address) {
        this.address = address;
    }
}
Was it helpful?

Solution

I recommend you using DTOs. Especially if your application has chances to grow (or is already big), you will have multiple situations like this or more complex: e.g you will want to show only some parts of your entities in a context, and some other parts in another context. An DTO is actually used to transport data, and is not an entity.

OTHER TIPS

@XmlTransient is recognized by JaxbAnnotationIntrospector that you are probably using:

@Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
    return m.getAnnotation(XmlTransient.class) != null;
}

so the easiest way is probably sub-classing it, and overriding the method. You can either just return 'false' in general, or, if you have to mask just one specific instance, try to match name of method or field to ensure that you block just one(s) you want to.

Pinchy

Did you try to use @JsonIgnore . You can add logic to display when the person has only one record. You need to create a duplicate variable.

something like this

@JsonIgnore public Address getAddress1() { return this.address; }

public void setAddress1(Address address1) {
    this.address = address1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top