简体   繁体   中英

JAXB, custom marshalling of relationships

I have an API which allows a third party to interact with my database via XML files which represent my java domains.

I use JAXB to define the xsd as well as marshal/un-marshal between my POJO and the XML.

The problem I face is how to support the equivalent of a hibernate lazy load. ie Only marshal objects recursively upon a certain condition. The condition I have in mind is something like what RequestFactory uses which is a .with(...) where the user can specify exactly which part of the object graph to return.

Consider the case where a "Person" has an "Image" in another table. When using the API and requests a "Person" I want to be able to specify .with(Image) or something equivalent, otherwise every use case gets penalised having to carry this image which
(a) is not required
(b) Has an unnecessary database hit.
I have 100+ tables and the permutations are too complex to code specialised POJO's.

How do I satisfy the above requirement using JAXB or any other free library.

One of possible simple solutions (assuming you use JPA entities with JAXB annotations but works as well with simple POJOs):

  • enrich each entity with some copying method - ie 'copyForExport'
  • this method creates unmanaged copy of an entity without values unwanted for the export
  • marshal your copy

Example:

@Entity
@XmlType
@XmlRootElement
@XmlAccessorType(value = XmlAccessType.FIELD)
public class SampleEntity {
    @Id private long id;
    @Column private String meaningful;
    @Column private String something1;
    @OneToMany private List<Something> something2;

    SampleEntity copyForExport() {
        SampleEntity copy = new SampleEntity();
        copy.id = id;
        copy.meaningful = meaningful;
        return copy;
    }
}

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