简体   繁体   English

仅在某些情况下使用@XmlTransient

[英]Use @XmlTransient only in some cases

I have two classes: 我有两节课:

public class A implements Serializable {
    ...
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "fieldID")
    private Collection<B> bCollection;
    ...
    public Collection<B> getBCollection()
    {
       return bCollection;
    }
    public void setBCollection(Collection<B> bCollection)
    {
       this.bCollection = bCollection;
    }
}

public class B implements Serializable {
    ...
    @JoinColumn(name = "aID", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private A aID;
    ...
    @XmlTransient
    public A getAID() {
       return aID;
    }
    public void setAID(A aID) {
       this.aID= aID;
    }
}

I was always using A class - it is working as inteded, but now, I want to use B class in RESTful GET method. 我一直在使用A类-它正在按原样工作,但是现在,我想在RESTful GET方法中使用B类。 However, when I try to do that, @XmlTransient prevents showing A field. 但是,当我尝试这样做时, @XmlTransient阻止显示A字段。 Is it possible to use @XmlTransient on A class, when I am using B class and to use it on B class, when I am using A class? 是否有可能使用@XmlTransientA班,当我使用B类,并把它用在B类,当我使用A类?

One easy solution is to include https://eclipse.org/eclipselink/moxy.php and start using @XmlInverseReference annotation for bi-directional dependencies. 一种简单的解决方案是包括https://eclipse.org/eclipselink/moxy.php并开始使用@XmlInverseReference批注进行双向依赖。 http://eclipse.org/eclipselink/api/2.2/org/eclipse/persistence/oxm/annotations/XmlInverseReference.html . http://eclipse.org/eclipselink/api/2.2/org/eclipse/persistence/oxm/annotations/XmlInverseReference.html

If it is not possible, please provide more information which JAXB/JAX-RS implementation you are using to be able to come up with some more concrete solution for your problem. 如果不可能,请提供更多信息,说明您正在使用哪种JAXB / JAX-RS实现,以便针对您的问题提出一些更具体的解决方案。

In general the idea is to control serialization process and decide how certain objects/fields are serialized and if those should be serialized at all. 通常,此想法是控制序列化过程,并决定如何序列化某些对象/字段以及是否应该完全序列化这些对象。 It can be achieved for example with following strategies: 例如,可以通过以下策略来实现:

  1. Serialize class B not as a whole object, but rather just as a String representation of it, when class A is serialized. 序列化类B时,它不是作为一个整体对象,而是序列化为类的String表示。 For example using @XmlAttribute @XmlIDREF . 例如,使用@XmlAttribute @XmlIDREF

  2. Control serialization process by setting up, for example, some kind of Filter/Exclusion (depending on what does your JAX-RS implementation provide): 通过设置(例如)某种过滤器/排除(取决于您的JAX-RS实现提供的内容)来控制序列化过程:

      ExclusionStrategy() { public boolean shouldSkipClass(Class<?> clazz) { return (clazz == B.class); } /** * Custom field exclusion goes here */ public boolean shouldSkipField(FieldAttributes f) { return false; } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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