JAXB,关系的自定义编组 [英] JAXB, custom marshalling of relationships

查看:153
本文介绍了JAXB,关系的自定义编组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API允许第三方通过代表我的java域的XML文件与我的数据库进行交互。

我使用JAXB来定义xsd以及我的POJO和XML之间的编组/非编组。

我面对的问题是如何支持相当于休眠延迟加载的问题。即在一定条件下递归地编组对象。我想到的情况就像RequestFactory使用的那样,它是一个.with(...),用户可以准确指定要返回的对象图的哪一部分。



考虑一个Person在另一个表中有Image的情况。当使用API​​并请求一个Person时,我希望能够指定.with(Image)或类似的东西,否则每个用例都会受到惩罚,不得不携带这张图片,而

(a)不是需要

(b)有不必要的数据库命中。

我有100多个表,这些排列过于复杂,无法编写专门的POJO。



如何使用JAXB或其他任何其他方法满足上述要求免费图书馆。

解决方案

可能的简单解决方案之一(假设您使用带有JAXB注释的JPA实体,但也适用于简单的POJO) p>


  • 使用某种复制方法丰富每个实体 - 即'copyForExport'
  • 此方法创建非托管副本没有值的实体出口不需要
  • 封送您的副本



示例:

  @Entity 
@XmlType
@XmlRootElement
@XmlAccessorType(value = XmlAccessType.FIELD)
public class SampleEntity {
@Id private long id;
@Column private String有意义;
@Column private String something1;
@OneToMany私人清单<东西> something2;

SampleEntity copyForExport(){
SampleEntity copy = new SampleEntity();
copy.id = id;
copy.meaningful =有意义的;
返回副本;
}
}


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. i.e. 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 - i.e. '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;
    }
}

这篇关于JAXB,关系的自定义编组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆